### MCP ESP32 Library Setup and Usage Source: https://context7.com/ertgtct/mcpesp/llms.txt Demonstrates the basic setup and usage of the MCP ESP32 library, including WiFi connection, server initialization, tool registration, and handling client requests. ```APIDOC ## MCP ESP32 Library Setup and Usage This section outlines the essential steps for setting up and using the MCP ESP32 library to create an MCP-compatible server on an ESP32 device. ### Initialization 1. **Include Headers**: Include necessary libraries like `` and ``. 2. **Instantiate Server**: Create an instance of the `Mcpesp` class. 3. **Connect to WiFi**: Establish a WiFi connection using `WiFi.begin()`. 4. **Initialize MCP Server**: Call `mcpServer.begin()` with a server name and version. ### Tool Registration 1. **Define Schema**: Create a `Schema` object to define the input parameters for your tool. 2. **Add Properties**: Use `schema.addProperty()` or `schema.addNumberProperty()` etc. to define individual parameters. 3. **Register Tool**: Call `mcpServer.addTool()` with the tool name, description, schema, and a callback function. ### Handling Client Requests - Call `mcpServer.handleClient()` within the `loop()` function to process incoming client requests. ### Example Code ```cpp #include #include Mcpesp mcpServer; // Standard callback signature: void callback(JsonObject arguments, JsonObject result) void calculateSum(JsonObject arguments, JsonObject result) { int a = arguments["a"].as(); int b = arguments["b"].as(); int sum = a + b; result["text"] = "The sum of " + String(a) + " and " + String(b) + " is " + String(sum); } void readGPIO(JsonObject arguments, JsonObject result) { int pin = arguments["pin"].as(); int value = digitalRead(pin); result["text"] = "GPIO " + String(pin) + " value: " + String(value); } void setup() { Serial.begin(115200); WiFi.begin("SSID", "PASSWORD"); while (WiFi.status() != WL_CONNECTED) { delay(500); } mcpServer.begin("Calculator Server", "1.0.0"); Schema sumSchema; sumSchema.addNumberProperty("a", "First number"); sumSchema.addNumberProperty("b", "Second number"); Schema gpioSchema; gpioSchema.addNumberProperty("pin", "GPIO pin number", 0, 39, 0, true); mcpServer.addTool("calculate_sum", "Add two numbers", sumSchema, calculateSum); mcpServer.addTool("read_gpio", "Read a GPIO pin value", gpioSchema, readGPIO); } void loop() { mcpServer.handleClient(); } ``` ``` -------------------------------- ### Quick Start: ESP32 MCP Server with LED Control Source: https://github.com/ertgtct/mcpesp/blob/master/README.md Demonstrates setting up an MCP server on an ESP32, connecting to WiFi, registering a tool to control an LED, and handling client requests. Ensure to replace 'YOUR_WIFI_SSID' and 'YOUR_WIFI_PASSWORD' with your actual credentials. ```cpp #include #include // WiFi credentials const char* ssid = "YOUR_WIFI_SSID"; const char* password = "YOUR_WIFI_PASSWORD"; // LED pin for demonstration #define LED_PIN 8 // Create MCP server instance Mcpesp mcpServer; void myToolCallback(JsonObject arguments, JsonObject result) { bool state = arguments["enabled"].as(); // Name of the property is "enabled" bool ledState = state; digitalWrite(LED_PIN, ledState ? LOW : HIGH); // LOW = ON for most ESP32 boards result["text"] = "LED turned " + String(state) + " successfully!"; Serial.println("LED state changed to: " + state); } void setup() { Serial.begin(115200); // Connect to WiFi WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("\nConnected!"); // Initialize MCP server mcpServer.begin("My MCP Server", "1.0.0"); // Create tool schema Schema toolSchema; toolSchema.addBooleanProperty("enabled", "Enable or disable feature"); // Register tool mcpServer.addTool( "my_tool", "Description of my tool", toolSchema, myToolCallback ); } void loop() { mcpServer.handleClient(); } ``` -------------------------------- ### List Available Tools Source: https://context7.com/ertgtct/mcpesp/llms.txt Use the `tools/list` method to get a list of all registered tools, including their names, descriptions, and input schemas. This is useful for discovering available functionalities. ```bash # List all available tools curl -X POST http://192.168.1.100/ \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {} }' # Response: # { # "id": 2, # "jsonrpc": "2.0", # "result": { # "tools": [ # { # "name": "toggle_led", # "description": "Toggle the LED on or off", # "inputSchema": { # "type": "object", # "properties": { # "state": { # "type": "boolean", ``` -------------------------------- ### Install Mcpesp Library with PlatformIO Source: https://github.com/ertgtct/mcpesp/blob/master/README.md Add the ArduinoJson dependency to your platformio.ini file for Mcpesp library compatibility. ```ini lib_deps = bblanchon/ArduinoJson@^7.0.0 ``` -------------------------------- ### tools/call - Execute a Tool Source: https://context7.com/ertgtct/mcpesp/llms.txt The `tools/call` method executes a registered tool with the provided arguments and returns the result. This section provides examples for calling the `toggle_led` and `get_sensor_data` tools. ```APIDOC ## POST /tools/call - Execute a Tool ### Description Executes a registered tool with the provided arguments and returns the result. ### Method POST ### Endpoint /tools/call ### Request Body ```json { "jsonrpc": "2.0", "id": "integer", "method": "tools/call", "params": { "name": "string", "arguments": { [Tool specific arguments] } } } ``` ### Request Example (toggle_led) ```bash curl -X POST http://192.168.1.100/ \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": { "name": "toggle_led", "arguments": { "state": true } } }' ``` ### Request Example (get_sensor_data) ```bash curl -X POST http://192.168.1.100/ \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": { "name": "get_sensor_data", "arguments": { "sensor": "temperature" } } }' ``` ### Response #### Success Response (200) ```json { "id": "integer", "jsonrpc": "2.0", "result": { "content": [ { "type": "text", "text": "string" } ] } } ``` #### Response Example (toggle_led) ```json { "id": 3, "jsonrpc": "2.0", "result": { "content": [ { "type": "text", "text": "LED turned on successfully!" } ] } } ``` #### Response Example (get_sensor_data) ```json { "id": 4, "jsonrpc": "2.0", "result": { "content": [ { "type": "text", "text": "Temperature: 24.3C, Humidity: 58%" } ] } } ``` ``` -------------------------------- ### Get JSON Schema Document Source: https://github.com/ertgtct/mcpesp/blob/master/README.md Call this function to retrieve the complete JSON schema document that has been built. ```javascript getSchema() ``` -------------------------------- ### Mcpesp Class: begin Method Source: https://github.com/ertgtct/mcpesp/blob/master/README.md Initializes the MCP server with a specified name, version, and port. ```cpp begin(serverName, version, port) ``` -------------------------------- ### begin() - Initialize the MCP Server Source: https://context7.com/ertgtct/mcpesp/llms.txt Initializes the MCP server with a specified name, version, and HTTP port. This method creates the underlying WebServer and sets up the root route handler. WiFi must be connected before calling this method. ```APIDOC ## begin() - Initialize the MCP Server ### Description Initializes the MCP server with a specified name, version, and HTTP port. This method creates the underlying WebServer and sets up the root route handler. WiFi must be connected before calling this method. ### Method `Mcpesp::begin(const char* name, const char* version, uint16_t port = 80)` ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```cpp #include #include const char* ssid = "YOUR_WIFI_SSID"; const char* password = "YOUR_WIFI_PASSWORD"; Mcpesp mcpServer; void setup() { Serial.begin(115200); // Connect to WiFi first WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("\nConnected! IP: " + WiFi.localIP().toString()); // Initialize MCP server with custom name and version mcpServer.begin("My Smart Home Controller", "2.0.0", 80); // Verify initialization if (mcpServer.isInitialized()) { Serial.println("MCP Server started successfully"); } } void loop() { mcpServer.handleClient(); } ``` ### Response #### Success Response (200) None (initialization is synchronous) #### Response Example None ``` -------------------------------- ### Create Mcpesp Server Instance Source: https://context7.com/ertgtct/mcpesp/llms.txt Instantiates the Mcpesp server with default configurations. WiFi must be connected separately before initialization. ```cpp #include #include // Create MCP server instance Mcpesp mcpServer; void setup() { Serial.begin(115200); // mcpServer is ready to be configured } ``` -------------------------------- ### Mcpesp Server Initialization and Tool Registration Source: https://github.com/ertgtct/mcpesp/blob/master/README.md Demonstrates how to initialize the Mcpesp server and register a new tool with its schema and callback function. ```APIDOC ## Mcpesp Server Initialization and Tool Registration ### Description This section details the process of setting up the Mcpesp server and adding custom tools that can be invoked via the Model Context Protocol. ### Methods #### `Mcpesp::begin(serverName, version, port)` Initializes the MCP server with a given name, version, and port. - **Parameters**: - `serverName` (const char*) - Name of the server (default: "ESP32 MCP Server") - `version` (const char*) - Server version (default: "1.0.0") - `port` (int) - HTTP server port (default: 80) #### `Mcpesp::addTool(name, description, inputSchema, callback)` Registers a new tool with the server, making it available through the MCP interface. - **Parameters**: - `name` (const String&) - Tool name (must be unique) - `description` (const String&) - Tool description - `inputSchema` (Schema&) - Schema defining the tool's input parameters - `callback` (toolCallback) - Function to be executed when the tool is called ### Request Example (Conceptual - C++ Code) ```cpp #include Mcpesp mcpServer; Schema toolSchema; toolSchema.addBooleanProperty("enabled", "Enable or disable feature"); void myToolCallback(JsonObject arguments, JsonObject result) { // Tool logic here result["text"] = "Operation successful"; } void setup() { mcpServer.begin("My ESP32 Server", "1.0.0"); mcpServer.addTool("my_tool", "A sample tool", toolSchema, myToolCallback); } ``` ### Response Example (Conceptual - JSON-RPC) ```json { "jsonrpc": "2.0", "id": 1, "result": { "text": "Operation successful" } } ``` ``` -------------------------------- ### Initialize Mcpesp Server with WiFi Source: https://context7.com/ertgtct/mcpesp/llms.txt Initializes the MCP server after connecting to WiFi. Requires WiFi credentials and specifies a custom server name, version, and HTTP port. ```cpp #include #include const char* ssid = "YOUR_WIFI_SSID"; const char* password = "YOUR_WIFI_PASSWORD"; Mcpesp mcpServer; void setup() { Serial.begin(115200); // Connect to WiFi first WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("\nConnected! IP: " + WiFi.localIP().toString()); // Initialize MCP server with custom name and version mcpServer.begin("My Smart Home Controller", "2.0.0", 80); // Verify initialization if (mcpServer.isInitialized()) { Serial.println("MCP Server started successfully"); } } void loop() { mcpServer.handleClient(); } ``` -------------------------------- ### Mcpesp Class: getServer Method Source: https://github.com/ertgtct/mcpesp/blob/master/README.md Retrieves the underlying WebServer instance for advanced configuration or direct interaction. ```cpp getServer() ``` -------------------------------- ### POST / - Initialize MCP Connection Source: https://context7.com/ertgtct/mcpesp/llms.txt The `initialize` method establishes an MCP connection and returns server capabilities. Send a JSON-RPC POST request to the root endpoint. ```APIDOC ## POST / ### Description Initializes an MCP connection and returns server capabilities. ### Method POST ### Endpoint / ### Request Body ```json { "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {} } ``` ### Response #### Success Response (200) ```json { "id": 1, "jsonrpc": "2.0", "result": { "protocolVersion": "2025-03-26", "capabilities": { "tools": { "listChanged": false } }, "serverInfo": { "name": "ESP32 MCP Server", "version": "1.0.0" } } } ``` ``` -------------------------------- ### Mcpesp Class Constructor Source: https://github.com/ertgtct/mcpesp/blob/master/README.md Initializes a new instance of the Mcpesp server. ```cpp Mcpesp() ``` -------------------------------- ### Mcpesp Class Constructor Source: https://context7.com/ertgtct/mcpesp/llms.txt Creates a new MCP server instance with default configuration. The server defaults to 'ESP32 MCP Server' name, version '1.0.0', and MCP protocol version '2025-03-26'. WiFi must be connected before initialization. ```APIDOC ## Mcpesp Class Constructor ### Description Creates a new MCP server instance with default configuration. ### Method Constructor ### Endpoint N/A ### Parameters None ### Request Example ```cpp #include #include // Create MCP server instance Mcpesp mcpServer; void setup() { Serial.begin(115200); // mcpServer is ready to be configured } ``` ### Response None ``` -------------------------------- ### POST / - tools/list - List Available Tools Source: https://context7.com/ertgtct/mcpesp/llms.txt The `tools/list` method returns all registered tools with their names, descriptions, and input schemas. ```APIDOC ## POST /tools/list ### Description Lists all registered tools with their names, descriptions, and input schemas. ### Method POST ### Endpoint / ### Request Body ```json { "jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {} } ``` ### Response #### Success Response (200) ```json { "id": 2, "jsonrpc": "2.0", "result": { "tools": [ { "name": "toggle_led", "description": "Toggle the LED on or off", "inputSchema": { "type": "object", "properties": { "state": { "type": "boolean" } } } } ] } } ``` ``` -------------------------------- ### Update Server Name and Version Source: https://context7.com/ertgtct/mcpesp/llms.txt Use this function after initialization to set the server name and version, which are included in the MCP initialize response. Ensure WiFi is connected before calling. ```cpp #include #include Mcpesp mcpServer; void setup() { Serial.begin(115200); WiFi.begin("SSID", "PASSWORD"); while (WiFi.status() != WL_CONNECTED) { delay(500); } mcpServer.begin(); // Update server info after initialization mcpServer.setServerInfo("Production ESP32 Controller", "3.1.0"); } void loop() { mcpServer.handleClient(); } ``` -------------------------------- ### Create Schema Instance Source: https://context7.com/ertgtct/mcpesp/llms.txt Instantiate a Schema object to define the structure and validation rules for tool input arguments. This schema follows the JSON Schema format. ```cpp #include void setup() { // Create empty schema Schema mySchema; // Schema is ready for adding properties } ``` -------------------------------- ### Initialize MCP Connection Source: https://context7.com/ertgtct/mcpesp/llms.txt Send a JSON-RPC POST request to the root endpoint to establish an MCP connection and retrieve server capabilities. This is the first step in interacting with the MCP server. ```bash # Initialize MCP connection curl -X POST http://192.168.1.100/ \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {} }' # Response: # { # "id": 1, # "jsonrpc": "2.0", # "result": { # "protocolVersion": "2025-03-26", # "capabilities": { # "tools": { # "listChanged": false # } # }, # "serverInfo": { # "name": "ESP32 MCP Server", # "version": "1.0.0" # } # } # } ``` -------------------------------- ### addTool() - Register a Tool with the Server Source: https://context7.com/ertgtct/mcpesp/llms.txt Registers a new tool with a name, description, input schema, and callback function. The tool becomes available via the MCP `tools/list` and `tools/call` methods. Tool names must be unique. ```APIDOC ## addTool() - Register a Tool with the Server ### Description Registers a new tool with a name, description, input schema, and callback function. The tool becomes available via the MCP `tools/list` and `tools/call` methods. Tool names must be unique. ### Method `void addTool(const char* name, const char* description, Schema& schema, ToolCallback callback)` ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```cpp #include #include const char* ssid = "YOUR_WIFI_SSID"; const char* password = "YOUR_WIFI_PASSWORD"; #define LED_PIN 8 Mcpesp mcpServer; // Tool callback function - receives arguments and populates result void toggleLed(JsonObject arguments, JsonObject result) { bool state = arguments["state"].as(); digitalWrite(LED_PIN, state ? LOW : HIGH); result["text"] = "LED turned " + String(state ? "on" : "off") + " successfully!"; } void getSensorData(JsonObject arguments, JsonObject result) { String sensorType = arguments["sensor"].as(); float temperature = 25.5 + random(-50, 50) / 10.0; int humidity = 60 + random(-20, 20); result["text"] = "Temperature: " + String(temperature, 1) + "C, Humidity: " + String(humidity) + "%"; } void setup() { Serial.begin(115200); pinMode(LED_PIN, OUTPUT); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); } mcpServer.begin("ESP32 LED & Sensor Server", "1.0.0"); // Create schema for LED control tool Schema ledSchema; ledSchema.addBooleanProperty("state", "LED state (true=on, false=off)"); // Create schema for sensor tool Schema sensorSchema; sensorSchema.addStringProperty("sensor", "Sensor type to read"); // Register tools mcpServer.addTool("toggle_led", "Toggle the LED on or off", ledSchema, toggleLed); mcpServer.addTool("get_sensor_data", "Get temperature and humidity data", sensorSchema, getSensorData); Serial.println("MCP Server ready at: http://" + WiFi.localIP().toString()); } void loop() { mcpServer.handleClient(); } ``` ### Response #### Success Response (200) None (tool registration is synchronous) #### Response Example None ``` -------------------------------- ### Call toggle_led Tool with curl Source: https://context7.com/ertgtct/mcpesp/llms.txt Execute the toggle_led tool to control an LED. Ensure the device is accessible at the specified IP address. ```bash # Call the toggle_led tool curl -X POST http://192.168.1.100/ \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": { "name": "toggle_led", "arguments": { "state": true } } }' ``` ```json { "id": 3, "jsonrpc": "2.0", "result": { "content": [ { "type": "text", "text": "LED turned on successfully!" } ] } } ``` -------------------------------- ### Register LED Toggle Tool Source: https://context7.com/ertgtct/mcpesp/llms.txt Registers a tool to toggle an LED, including its input schema and callback function. The callback function receives arguments and updates a result object. ```cpp #include #include const char* ssid = "YOUR_WIFI_SSID"; const char* password = "YOUR_WIFI_PASSWORD"; #define LED_PIN 8 Mcpesp mcpServer; // Tool callback function - receives arguments and populates result void toggleLed(JsonObject arguments, JsonObject result) { bool state = arguments["state"].as(); digitalWrite(LED_PIN, state ? LOW : HIGH); result["text"] = "LED turned " + String(state ? "on" : "off") + " successfully!"; } void getSensorData(JsonObject arguments, JsonObject result) { String sensorType = arguments["sensor"].as(); float temperature = 25.5 + random(-50, 50) / 10.0; int humidity = 60 + random(-20, 20); result["text"] = "Temperature: " + String(temperature, 1) + "C, Humidity: " + String(humidity) + "%"; } void setup() { Serial.begin(115200); pinMode(LED_PIN, OUTPUT); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); } mcpServer.begin("ESP32 LED & Sensor Server", "1.0.0"); // Create schema for LED control tool Schema ledSchema; ledSchema.addBooleanProperty("state", "LED state (true=on, false=off)"); // Create schema for sensor tool Schema sensorSchema; sensorSchema.addStringProperty("sensor", "Sensor type to read"); // Register tools mcpServer.addTool("toggle_led", "Toggle the LED on or off", ledSchema, toggleLed); mcpServer.addTool("get_sensor_data", "Get temperature and humidity data", sensorSchema, getSensorData); Serial.println("MCP Server ready at: http://" + WiFi.localIP().toString()); } void loop() { mcpServer.handleClient(); } ``` -------------------------------- ### getServer() - Access Underlying WebServer Source: https://context7.com/ertgtct/mcpesp/llms.txt Returns a pointer to the underlying ESP32 WebServer instance for advanced configuration such as adding custom routes or middleware. ```APIDOC ## getServer() ### Description Returns a pointer to the underlying ESP32 WebServer instance for advanced configuration such as adding custom routes or middleware. ### Method `WebServer* getServer()` ### Parameters None ### Request Example ```cpp #include #include Mcpesp mcpServer; void handleStatus() { WebServer* server = mcpServer.getServer(); server->send(200, "application/json", "{\"status\":\"online\",\"uptime\":" + String(millis()) + "}"); } void setup() { Serial.begin(115200); WiFi.begin("SSID", "PASSWORD"); while (WiFi.status() != WL_CONNECTED) { delay(500); } mcpServer.begin("ESP32 MCP Server", "1.0.0"); // Add custom route using the underlying WebServer WebServer* server = mcpServer.getServer(); server->on("/status", handleStatus); } void loop() { mcpServer.handleClient(); } ``` ### Response - **WebServer*** - A pointer to the underlying ESP32 WebServer instance. #### Success Response (200) N/A (This method returns a pointer, not a response to a request) #### Response Example N/A ``` -------------------------------- ### setServerInfo() - Update Server Name and Version Source: https://context7.com/ertgtct/mcpesp/llms.txt Updates the server name and version after initialization. This information is returned in the MCP `initialize` response. ```APIDOC ## setServerInfo() ### Description Updates the server name and version after initialization. This information is returned in the MCP `initialize` response. ### Method `setServerInfo(const char* serverName, const char* serverVersion)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```cpp #include #include Mcpesp mcpServer; void setup() { Serial.begin(115200); WiFi.begin("SSID", "PASSWORD"); while (WiFi.status() != WL_CONNECTED) { delay(500); } mcpServer.begin(); // Update server info after initialization mcpServer.setServerInfo("Production ESP32 Controller", "3.1.0"); } void loop() { mcpServer.handleClient(); } ``` ### Response None (This is a configuration method) #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Schema Class Constructor Source: https://github.com/ertgtct/mcpesp/blob/master/README.md Creates a new instance of the Schema class for defining tool input parameters. ```cpp Schema() ``` -------------------------------- ### Mcpesp Class: isInitialized Method Source: https://github.com/ertgtct/mcpesp/blob/master/README.md Checks if the MCP server has been successfully initialized. ```cpp isInitialized() ``` -------------------------------- ### Schema Class - Constructor Source: https://context7.com/ertgtct/mcpesp/llms.txt Creates a new schema instance for defining tool input parameters. The schema follows JSON Schema format and is used to validate incoming tool arguments. ```APIDOC ## Schema Constructor ### Description Creates a new schema instance for defining tool input parameters. The schema follows JSON Schema format and is used to validate incoming tool arguments. ### Method `Schema()` ### Parameters None ### Request Example ```cpp #include void setup() { // Create empty schema Schema mySchema; // Schema is ready for adding properties } ``` ### Response None (This is a constructor) #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Mcpesp Class: addTool Method Source: https://github.com/ertgtct/mcpesp/blob/master/README.md Registers a new tool with the MCP server, including its name, description, input schema, and a callback function. ```cpp addTool(name, description, inputSchema, callback) ``` -------------------------------- ### Schema Class: addStringProperty Method Source: https://github.com/ertgtct/mcpesp/blob/master/README.md Adds a string property to the schema, specifying its name, description, and whether it is required. ```cpp addStringProperty(name, description, required) ``` -------------------------------- ### Mcpesp Class: setServerInfo Method Source: https://github.com/ertgtct/mcpesp/blob/master/README.md Updates the server's name and version information. ```cpp setServerInfo(name, version) ``` -------------------------------- ### handleClient() - Process Incoming Requests Source: https://context7.com/ertgtct/mcpesp/llms.txt Handles incoming HTTP client requests. This method must be called in the `loop()` function to process JSON-RPC requests from MCP clients. ```APIDOC ## handleClient() - Process Incoming Requests ### Description Handles incoming HTTP client requests. This method must be called in the `loop()` function to process JSON-RPC requests from MCP clients. ### Method `void handleClient()` ### Endpoint N/A ### Parameters None ### Request Example ```cpp #include #include Mcpesp mcpServer; void setup() { Serial.begin(115200); WiFi.begin("SSID", "PASSWORD"); while (WiFi.status() != WL_CONNECTED) { delay(500); } mcpServer.begin("ESP32 MCP Server", "1.0.0"); } void loop() { // Must be called continuously to handle incoming MCP requests mcpServer.handleClient(); // Other loop code can go here delay(10); } ``` ### Response None (this method processes requests and does not return a direct response to the caller, but rather handles the client communication internally) ``` -------------------------------- ### Tool Callback Function Source: https://github.com/ertgtct/mcpesp/blob/master/README.md Signature and description of the tool callback function. ```APIDOC ## Tool Callback Function Tool callbacks have the following signature: ```cpp void toolCallback(JsonObject arguments, JsonObject result) ``` ### Parameters - **arguments** (JsonObject) - Input parameters from the client - **result** (JsonObject) - Result object to populate (set `result["text"]` for the response) ### Returns void ``` -------------------------------- ### Mcpesp Class: handleClient Method Source: https://github.com/ertgtct/mcpesp/blob/master/README.md Continuously handles incoming client requests for the MCP server. This method should be called within the main loop. ```cpp handleClient() ``` -------------------------------- ### MCP Protocol Methods Source: https://github.com/ertgtct/mcpesp/blob/master/README.md Core methods implemented by the MCP Protocol. ```APIDOC ## MCP Protocol This library implements the following MCP methods: - `initialize`: Initializes the MCP connection - `tools/list`: Lists all registered tools - `tools/call`: Calls a registered tool All methods follow the JSON-RPC 2.0 specification and return appropriate responses. ``` -------------------------------- ### Tool Callback Function Signature Source: https://github.com/ertgtct/mcpesp/blob/master/README.md This is the signature for the tool callback function. It receives input arguments and a result object to populate the response. ```cpp void toolCallback(JsonObject arguments, JsonObject result) ``` -------------------------------- ### Call get_sensor_data Tool with curl Source: https://context7.com/ertgtct/mcpesp/llms.txt Execute the get_sensor_data tool to retrieve temperature or humidity readings. Specify the sensor type in the arguments. ```bash # Call the get_sensor_data tool curl -X POST http://192.168.1.100/ \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": { "name": "get_sensor_data", "arguments": { "sensor": "temperature" } } }' ``` ```json { "id": 4, "jsonrpc": "2.0", "result": { "content": [ { "type": "text", "text": "Temperature: 24.3C, Humidity: 58%" } ] } } ``` -------------------------------- ### Access Underlying WebServer Source: https://context7.com/ertgtct/mcpesp/llms.txt Retrieve a pointer to the underlying ESP32 WebServer instance to configure custom routes or middleware. This allows for advanced web server configurations beyond the MCP library's standard features. ```cpp #include #include Mcpesp mcpServer; void handleStatus() { WebServer* server = mcpServer.getServer(); server->send(200, "application/json", "{\"status\":\"online\",\"uptime\":" + String(millis()) + "}"); } void setup() { Serial.begin(115200); WiFi.begin("SSID", "PASSWORD"); while (WiFi.status() != WL_CONNECTED) { delay(500); } mcpServer.begin("ESP32 MCP Server", "1.0.0"); // Add custom route using the underlying WebServer WebServer* server = mcpServer.getServer(); server->on("/status", handleStatus); } void loop() { mcpServer.handleClient(); } ``` -------------------------------- ### Mcpesp Server Client Handling and Information Management Source: https://github.com/ertgtct/mcpesp/blob/master/README.md Covers methods for handling incoming client requests and managing server information. ```APIDOC ## Mcpesp Server Client Handling and Information Management ### Description This section describes how to handle incoming client requests and manage the server's metadata. ### Methods #### `Mcpesp::handleClient()` Processes incoming HTTP requests for the MCP server. This should be called regularly in the main loop. - **Returns**: - void #### `Mcpesp::setServerInfo(name, version)` Updates the server's name and version information. - **Parameters**: - `name` (const String&) - The new name for the server. - `version` (const String&) - The new version for the server. #### `Mcpesp::setProtocolVersion(version)` Sets the version of the Model Context Protocol the server adheres to. - **Parameters**: - `version` (const String&) - The MCP protocol version string (default: "2025-03-26"). #### `Mcpesp::isInitialized()` Checks if the MCP server has been successfully initialized. - **Returns**: - bool - `true` if initialized, `false` otherwise. #### `Mcpesp::getServer()` Retrieves a pointer to the underlying WebServer instance, allowing for advanced configurations. - **Returns**: - WebServer* - Pointer to the WebServer object. ### Request Example (Conceptual - C++ Code) ```cpp void loop() { mcpServer.handleClient(); // Handle incoming requests // Other loop tasks... } void setup() { // ... server initialization ... mcpServer.setServerInfo("My Advanced Server", "2.0.0"); mcpServer.setProtocolVersion("2025-03-26"); } ``` ``` -------------------------------- ### Set MCP Protocol Version Source: https://context7.com/ertgtct/mcpesp/llms.txt Set a custom MCP protocol version string that will be returned in the initialize response. The default is "2025-03-26". Ensure the server is initialized before setting the protocol version. ```cpp #include #include Mcpesp mcpServer; void setup() { Serial.begin(115200); WiFi.begin("SSID", "PASSWORD"); while (WiFi.status() != WL_CONNECTED) { delay(500); } mcpServer.begin("ESP32 MCP Server", "1.0.0"); // Set custom protocol version mcpServer.setProtocolVersion("2024-11-05"); } void loop() { mcpServer.handleClient(); } ``` -------------------------------- ### Schema Class for Tool Input Definition Source: https://github.com/ertgtct/mcpesp/blob/master/README.md Documentation for the Schema class used to define input parameters for MCP tools. ```APIDOC ## Schema Class for Tool Input Definition ### Description The `Schema` class is used to define the structure and types of input parameters required by an MCP tool. ### Methods #### `Schema()` Constructor for the `Schema` class. #### `addStringProperty(name, description, required)` Adds a string property to the schema. - **Parameters**: - `name` (String) - The name of the property. - `description` (String) - A description of the property's purpose. - `required` (bool) - Indicates if this property is mandatory (default: `true`). ### Request Example (Conceptual - C++ Code) ```cpp #include Schema mySchema; mySchema.addStringProperty("username", "The user's name", true); mySchema.addStringProperty("email", "The user's email address", false); // Optional // This schema can then be passed to Mcpesp::addTool ``` ``` -------------------------------- ### Mcpesp Tool Callback Function Signature Source: https://context7.com/ertgtct/mcpesp/llms.txt Implement tool callbacks in C++ to handle incoming arguments and populate a result JsonObject. The 'text' field in the result is returned to the MCP client. ```cpp #include #include Mcpesp mcpServer; // Standard callback signature: void callback(JsonObject arguments, JsonObject result) void calculateSum(JsonObject arguments, JsonObject result) { // Extract arguments by name int a = arguments["a"].as(); int b = arguments["b"].as(); // Perform operation int sum = a + b; // Set result text - this is returned to the MCP client result["text"] = "The sum of " + String(a) + " and " + String(b) + " is " + String(sum); } void readGPIO(JsonObject arguments, JsonObject result) { int pin = arguments["pin"].as(); // Read the GPIO pin int value = digitalRead(pin); // Return formatted result result["text"] = "GPIO " + String(pin) + " value: " + String(value); } void setup() { Serial.begin(115200); WiFi.begin("SSID", "PASSWORD"); while (WiFi.status() != WL_CONNECTED) { delay(500); } mcpServer.begin("Calculator Server", "1.0.0"); Schema sumSchema; sumSchema.addNumberProperty("a", "First number"); sumSchema.addNumberProperty("b", "Second number"); Schema gpioSchema; gpioSchema.addNumberProperty("pin", "GPIO pin number", 0, 39, 0, true); mcpServer.addTool("calculate_sum", "Add two numbers", sumSchema, calculateSum); mcpServer.addTool("read_gpio", "Read a GPIO pin value", gpioSchema, readGPIO); } void loop() { mcpServer.handleClient(); } ``` -------------------------------- ### setProtocolVersion() - Set MCP Protocol Version Source: https://context7.com/ertgtct/mcpesp/llms.txt Sets the MCP protocol version string returned in the `initialize` response. Default is "2025-03-26". ```APIDOC ## setProtocolVersion() ### Description Sets the MCP protocol version string returned in the `initialize` response. Default is "2025-03-26". ### Method `setProtocolVersion(const char* protocolVersion)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```cpp #include #include Mcpesp mcpServer; void setup() { Serial.begin(115200); WiFi.begin("SSID", "PASSWORD"); while (WiFi.status() != WL_CONNECTED) { delay(500); } mcpServer.begin("ESP32 MCP Server", "1.0.0"); // Set custom protocol version mcpServer.setProtocolVersion("2024-11-05"); } void loop() { mcpServer.handleClient(); } ``` ### Response None (This is a configuration method) #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Handle Incoming Mcpesp Requests Source: https://context7.com/ertgtct/mcpesp/llms.txt Continuously processes incoming HTTP client requests for the MCP server. This method must be called within the `loop()` function. ```cpp #include #include Mcpesp mcpServer; void setup() { Serial.begin(115200); WiFi.begin("SSID", "PASSWORD"); while (WiFi.status() != WL_CONNECTED) { delay(500); } mcpServer.begin("ESP32 MCP Server", "1.0.0"); } void loop() { // Must be called continuously to handle incoming MCP requests mcpServer.handleClient(); // Other loop code can go here delay(10); } ``` -------------------------------- ### Schema Building Functions Source: https://github.com/ertgtct/mcpesp/blob/master/README.md Functions to programmatically build JSON schemas for tools. ```APIDOC ## Schema Building Functions ### `addStringEnumProperty(name, description, options, required)` Adds a string enum property to the schema. ### Parameters #### Path Parameters - **name** (String) - Required - Property name - **description** (String) - Required - Property description - **options** (String[]) - Required - Array of allowed values - **required** (bool) - Optional - Whether the property is required (default: true) ### Returns void ### `addNumberProperty(name, description, required)` Adds a number property to the schema. ### Parameters #### Path Parameters - **name** (String) - Required - Property name - **description** (String) - Required - Property description - **required** (bool) - Optional - Whether the property is required (default: true) ### Returns void ### `addNumberProperty(name, description, min, max, def, required)` Adds a number property with constraints to the schema. ### Parameters #### Path Parameters - **name** (String) - Required - Property name - **description** (String) - Required - Property description - **min** (int) - Required - Minimum value - **max** (int) - Required - Maximum value - **def** (int) - Required - Default value - **required** (bool) - Optional - Whether the property is required (default: true) ### Returns void ### `addBooleanProperty(name, description, required)` Adds a boolean property to the schema. ### Parameters #### Path Parameters - **name** (String) - Required - Property name - **description** (String) - Required - Property description - **required** (bool) - Optional - Whether the property is required (default: true) ### Returns void ### `getSchema()` Returns the JSON schema document. ### Returns JsonDocument ``` -------------------------------- ### Schema - addStringProperty() Source: https://context7.com/ertgtct/mcpesp/llms.txt Adds a string property to the schema with a name, description, and optional required flag (default: true). ```APIDOC ## addStringProperty() ### Description Adds a string property to the schema with a name, description, and optional required flag (default: true). ### Method `void addStringProperty(const char* name, const char* description, bool required = true)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```cpp #include #include Mcpesp mcpServer; void sendMessage(JsonObject arguments, JsonObject result) { String message = arguments["message"].as(); String recipient = arguments["recipient"].as(); result["text"] = "Sent '" + message + "' to " + recipient; } void setup() { Serial.begin(115200); WiFi.begin("SSID", "PASSWORD"); while (WiFi.status() != WL_CONNECTED) { delay(500); } mcpServer.begin("Messaging Server", "1.0.0"); Schema messageSchema; messageSchema.addStringProperty("message", "The message content to send", true); messageSchema.addStringProperty("recipient", "The recipient address", true); messageSchema.addStringProperty("note", "Optional note", false); // Optional parameter mcpServer.addTool("send_message", "Send a message", messageSchema, sendMessage); } void loop() { mcpServer.handleClient(); } ``` ### Response None (This is a configuration method) #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Tool Callback Function Signature Source: https://context7.com/ertgtct/mcpesp/llms.txt Defines the standard signature for tool callback functions, which receive input arguments and populate a result JsonObject. The 'text' field of the result is returned to the MCP client. ```APIDOC ## Tool Callback Function Signature Tool callbacks receive a JsonObject with input arguments and must populate a result JsonObject. The result's "text" field is returned to the MCP client. ### Signature ```cpp void callback(JsonObject arguments, JsonObject result) ``` ### Parameters - **arguments** (JsonObject) - A JSON object containing the input arguments for the tool. - **result** (JsonObject) - A JSON object to populate with the tool's output. The `result["text"]` field is returned to the client. ### Example Implementation (calculateSum) ```cpp void calculateSum(JsonObject arguments, JsonObject result) { // Extract arguments by name int a = arguments["a"].as(); int b = arguments["b"].as(); // Perform operation int sum = a + b; // Set result text - this is returned to the MCP client result["text"] = "The sum of " + String(a) + " and " + String(b) + " is " + String(sum); } ``` ### Example Implementation (readGPIO) ```cpp void readGPIO(JsonObject arguments, JsonObject result) { int pin = arguments["pin"].as(); // Read the GPIO pin int value = digitalRead(pin); // Return formatted result result["text"] = "GPIO " + String(pin) + " value: " + String(value); } ``` ```