> ## Documentation Index
> Fetch the complete documentation index at: https://docs.coreflux.org/llms.txt
> Use this file to discover all available pages before exploring further.

# MCP Routes

> Connect your Coreflux broker to external tools and services through the Model Context Protocol (MCP)

## Plug Your Broker Into Any MCP Tool

MCP (Model Context Protocol) is an open standard that defines how applications communicate with external tool servers. MCP Routes let your Coreflux broker connect to any MCP-compatible server — file systems, messaging platforms, cloud storage, spreadsheets, and more — and call their tools directly from LoT Actions.

<Tip>
  **Like adding power tools to a workbench.** Each MCP Route plugs a new tool into your broker — a Slack server for sending messages, a filesystem server for reading logs, a Google Drive server for cloud backups. Once connected, any LoT Action can pick up and use that tool.
</Tip>

***

## Integration Architecture

MCP Routes allow the Coreflux Broker to connect to external MCP servers as a **client**. This enables LoT Actions to call tools provided by any MCP server—file systems, cloud services, communication platforms, and more.

```mermaid actions={false} theme={null}
graph LR
    subgraph mcpServers [External MCP Servers]
        Filesystem[Filesystem Server]
        Slack[Slack Server]
        GDrive[Google Drive]
        Custom[Custom MCP Server]
    end
    
    subgraph broker [Coreflux Broker]
        MCPRoutes[MCP Routes]
        Actions[LoT Actions]
        Topics[MQTT Topics]
    end
    
    subgraph devices [IoT Layer]
        Sensors[Sensors]
        Actuators[Actuators]
    end
    
    MCPRoutes -->|connects to| Filesystem
    MCPRoutes -->|connects to| Slack
    MCPRoutes -->|connects to| GDrive
    MCPRoutes -->|connects to| Custom
    
    Actions -->|CALL MCP| MCPRoutes
    Actions -->|PUBLISH/KEEP| Topics
    Topics <--> Sensors
    Topics <--> Actuators
```

### How It Works

1. **Define MCP Routes** - Each route connects to an external MCP server
2. **Discover Tools** - The broker discovers available tools from each server
3. **Call from Actions** - Use `CALL MCP` in LoT Actions to invoke any tool
4. **Reusable Connections** - Multiple actions can share the same MCP route

<Tip>
  **MCP as a Connection Type.** Just like database routes or REST API routes, MCP routes provide a reusable connection that any action can leverage. Define the route once, use it everywhere.
</Tip>

***

## In This Page

| Section                                           | Description                                       |
| ------------------------------------------------- | ------------------------------------------------- |
| [Basic Syntax](#basic-syntax)                     | Define an MCP route                               |
| [Configuration](#mcp-configuration)               | Server command, arguments, and client name        |
| [Configuration Examples](#configuration-examples) | Filesystem, custom, and Node.js server setups     |
| [MCP Server Examples](#mcp-server-examples)       | Node.js and Python MCP servers for IoT            |
| [Calling MCP Tools](#calling-mcp-tools)           | Execute MCP tools from LoT Actions                |
| [Tool Discovery](#tool-discovery)                 | Discover available tools via MQTT system topics   |
| [Use Cases](#use-cases)                           | Common MCP integration patterns                   |
| [Best Practices](#best-practices)                 | Security, resource management, and error handling |

***

## Basic Syntax

The `MCP` route type connects your Coreflux broker to an external MCP server, making that server's tools callable from LoT Actions. Each route manages one MCP server connection, and you can define multiple routes to connect to different servers simultaneously.

```lot theme={null}
DEFINE ROUTE MCPFilesystem WITH TYPE MCP
    ADD MCP_CONFIG
        WITH SERVER_COMMAND "npx"
        WITH SERVER_ARGUMENTS "-y, @modelcontextprotocol/server-filesystem, /data"
        WITH CLIENT_NAME "CorefluxFS"
```

Once connected, any LoT Action can use `CALL MCP` to invoke the server's tools — send Slack messages, read and write files, generate spreadsheet reports, or interact with any other MCP-compatible service.

***

## MCP Configuration

### MCP\_CONFIG Parameters

<ParamField path="SERVER_COMMAND" type="string">
  MCP server command to execute (e.g., `npx`, `python`, `node`).
</ParamField>

<ParamField path="SERVER_ARGUMENTS" type="string">
  Comma-separated server arguments (e.g., `-y, @modelcontextprotocol/server-filesystem`).
</ParamField>

<ParamField path="CLIENT_NAME" type="string">
  MCP client identifier. Default: CorefluxBroker.
</ParamField>

***

## Configuration Examples

<Tabs>
  <Tab title="Filesystem Server">
    Enable LoT Actions to perform file operations:

    ```lot theme={null}
    DEFINE ROUTE MCPFilesystem WITH TYPE MCP
        ADD MCP_CONFIG
            WITH SERVER_COMMAND "npx"
            WITH SERVER_ARGUMENTS "-y, @modelcontextprotocol/server-filesystem, /data"
            WITH CLIENT_NAME "CorefluxFS"
    ```
  </Tab>

  <Tab title="Custom MCP Server">
    Connect to a custom MCP server:

    ```lot theme={null}
    DEFINE ROUTE MCPCustom WITH TYPE MCP
        ADD MCP_CONFIG
            WITH SERVER_COMMAND "python"
            WITH SERVER_ARGUMENTS "-m, my_mcp_server"
            WITH CLIENT_NAME "CorefluxCustom"
    ```
  </Tab>

  <Tab title="Node.js Server">
    Run a Node.js MCP server:

    ```lot theme={null}
    DEFINE ROUTE MCPNode WITH TYPE MCP
        ADD MCP_CONFIG
            WITH SERVER_COMMAND "node"
            WITH SERVER_ARGUMENTS "/opt/mcp/server.js, --config, /etc/mcp/config.json"
            WITH CLIENT_NAME "CorefluxNode"
    ```
  </Tab>
</Tabs>

***

## MCP Server Examples

The MCP ecosystem includes servers for various platforms and services. These examples show how to connect popular MCP servers to your Coreflux broker for IoT integration.

<Tabs>
  <Tab title="Node.js Servers (npx)">
    Node.js-based MCP servers can be run directly using `npx`. These are the most common and include official Anthropic servers.

    | Server              | LoT Configuration                                                                                   | IoT Use Case                          |
    | ------------------- | --------------------------------------------------------------------------------------------------- | ------------------------------------- |
    | **Filesystem**      | `SERVER_COMMAND "npx"` with `SERVER_ARGUMENTS "-y, @modelcontextprotocol/server-filesystem, /data"` | Read sensor logs, manage config files |
    | **Google Drive**    | `SERVER_COMMAND "npx"` with `SERVER_ARGUMENTS "-y, @modelcontextprotocol/server-gdrive"`            | Cloud backup of IoT data              |
    | **Slack**           | `SERVER_COMMAND "npx"` with `SERVER_ARGUMENTS "-y, @modelcontextprotocol/server-slack"`             | Send alerts to team channels          |
    | **Memory**          | `SERVER_COMMAND "npx"` with `SERVER_ARGUMENTS "-y, @modelcontextprotocol/server-memory"`            | Persist context across AI sessions    |
    | **Fetch**           | `SERVER_COMMAND "npx"` with `SERVER_ARGUMENTS "-y, @modelcontextprotocol/server-fetch"`             | Access external APIs and web data     |
    | **Windows Control** | `SERVER_COMMAND "npx"` with `SERVER_ARGUMENTS "-y, mcp-control"`                                    | Automate HMI/SCADA systems            |

    **Example: Slack Alerts for IoT Events**

    ```lot theme={null}
    DEFINE ROUTE MCPSlack WITH TYPE MCP
        ADD MCP_CONFIG
            WITH SERVER_COMMAND "npx"
            WITH SERVER_ARGUMENTS "-y, @modelcontextprotocol/server-slack"
            WITH CLIENT_NAME "CorefluxSlack"
    ```
  </Tab>

  <Tab title="Python Servers (uvx)">
    Python-based MCP servers use `uvx` (the uv package runner). These are common for third-party integrations.

    | Server      | LoT Configuration                                                 | IoT Use Case                      |
    | ----------- | ----------------------------------------------------------------- | --------------------------------- |
    | **Spotify** | `SERVER_COMMAND "uvx"` with `SERVER_ARGUMENTS "spotify-mcp"`      | Smart home audio control          |
    | **Excel**   | `SERVER_COMMAND "uvx"` with `SERVER_ARGUMENTS "excel-mcp-server"` | Generate reports from sensor data |

    **Example: Excel Reports from Sensor Data**

    ```lot theme={null}
    DEFINE ROUTE MCPExcel WITH TYPE MCP
        ADD MCP_CONFIG
            WITH SERVER_COMMAND "uvx"
            WITH SERVER_ARGUMENTS "excel-mcp-server"
            WITH CLIENT_NAME "CorefluxExcel"
    ```
  </Tab>
</Tabs>

***

## Calling MCP Tools

Once an MCP route is defined, you can call its tools from within LoT Actions using the `CALL MCP` syntax. This enables AI-powered automation triggered by MQTT events.

### Basic Syntax

The standard syntax to invoke an MCP tool from an Action:

```lot theme={null}
CALL MCP "RouteName.ToolName"
    WITH (arg1 = value1, arg2 = value2)
    RETURN AS {result_variable}
```

| Component      | Format                     | Description                                 |
| -------------- | -------------------------- | ------------------------------------------- |
| **Route.Tool** | `"RouteName.ToolName"`     | Route name and tool name separated by a dot |
| **WITH**       | `WITH (name = value, ...)` | Named arguments in parentheses              |
| **RETURN AS**  | `RETURN AS {varname}`      | Capture the result in a variable            |

### Complete Example

This Action monitors a temperature sensor and uses an MCP tool to send a Slack message when the temperature exceeds a threshold:

```lot theme={null}
DEFINE ACTION TemperatureAlert
ON TOPIC "sensors/+/temperature" DO
    SET "temp" WITH (GET JSON "value" IN PAYLOAD AS DOUBLE)
    SET "sensor_id" WITH TOPIC POSITION 2
    
    IF {temp} > 80 THEN
        CALL MCP "MCPSlack.send-message"
            WITH (channel = "alerts", message = "🔥 Sensor " + {sensor_id} + " at " + {temp} + "°C")
            RETURN AS {result}
        
        PUBLISH TOPIC "alerts/temperature/sent" WITH "Sensor: " + {sensor_id} + " Temp: " + {temp} + " Result: " + {result}
    END IF
```

### Syntax Variations

<AccordionGroup>
  <Accordion title="No Arguments">
    Some tools don't require arguments:

    ```lot theme={null}
    CALL MCP "MCPSystem.get-status"
        RETURN AS {status}
    ```
  </Accordion>

  <Accordion title="Multiple Arguments">
    Pass multiple named parameters:

    ```lot theme={null}
    CALL MCP "MCPFilesystem.write-file"
        WITH (path = "/data/log.txt", content = {payload}, append = true)
        RETURN AS {write_result}
    ```
  </Accordion>

  <Accordion title="String Concatenation">
    Build dynamic values using expressions:

    ```lot theme={null}
    CALL MCP "MCPSlack.send-message"
        WITH (message = "Device " + {device_id} + " reported: " + {value} + " at " + TIMESTAMP "UTC")
        RETURN AS {chat_result}
    ```
  </Accordion>
</AccordionGroup>

***

## Tool Discovery

When an MCP route connects to a server, Coreflux automatically discovers all available tools and publishes them to MQTT system topics. This allows you to dynamically query what tools are available.

### System Topics

| Topic                                               | Description                       |
| --------------------------------------------------- | --------------------------------- |
| `$SYS/Coreflux/Routes/{RouteName}/Tools`            | Summary of all tools for a route  |
| `$SYS/Coreflux/Routes/{RouteName}/Tools/{ToolName}` | Detailed info for a specific tool |

### Tools Summary Payload

Subscribe to the summary topic to see all available tools:

```json theme={null}
{
  "route_name": "MCPSlack",
  "route_type": "MCP",
  "total_tools": 8,
  "tools": ["send-message", "list-channels", "get-channel-history", "add-reaction", ...],
  "timestamp": "2025-12-31T12:00:00.000Z"
}
```

### Individual Tool Payload

Each tool publishes detailed metadata including parameters and usage examples:

```json theme={null}
{
  "name": "send-message",
  "route_name": "MCPSlack",
  "tool_type": "MCP",
  "description": "Send a message to a Slack channel",
  "parameters": {
    "channel": { "type": "string", "required": true },
    "message": { "type": "string", "required": true }
  },
  "usage_example": "CALL MCP \"MCPSlack.send-message\" WITH (channel = {channel}, message = {message}) RETURN AS {result}",
  "capability": {
    "execution_count": 42,
    "average_latency_ms": 150.25,
    "reliability_percent": 98.5
  },
  "timestamp": "2025-12-31T12:00:00.000Z"
}
```

### Subscribing to Tool Discovery

Use MQTT Explorer or any MQTT client to discover available tools:

| What to Find                    | Topic Pattern                                      |
| ------------------------------- | -------------------------------------------------- |
| All tools for a specific route  | `$SYS/Coreflux/Routes/MCPSlack/Tools`              |
| Details for a specific tool     | `$SYS/Coreflux/Routes/MCPSlack/Tools/send-message` |
| All tools across all MCP routes | `$SYS/Coreflux/Routes/+/Tools/#`                   |

<Note>
  Tool discovery topics are **retained messages**, so the information is immediately available when you subscribe—you don't need to wait for the next update.
</Note>

***

## Use Cases

<AccordionGroup>
  <Accordion title="Alerting and Notifications" icon="bell">
    Connect to Slack, email, or other messaging MCP servers to send alerts directly from LoT Actions. When a sensor crosses a threshold, the Action calls the messaging tool — no external middleware needed.
  </Accordion>

  <Accordion title="File and Data Management" icon="folder-open">
    Use filesystem MCP servers to read configuration files, write sensor logs, or manage data exports. LoT Actions can read a config file at startup or append readings to a log file on every event.
  </Accordion>

  <Accordion title="Cloud Integration" icon="cloud">
    Connect to Google Drive, Excel, or other cloud MCP servers to back up IoT data, generate reports from sensor readings, or sync configurations with cloud storage.
  </Accordion>

  <Accordion title="External Automation" icon="gears">
    Use Windows Control or custom MCP servers to automate HMI/SCADA interfaces, trigger external scripts, or interact with desktop applications as part of your IoT workflow.
  </Accordion>
</AccordionGroup>

***

## Best Practices

<AccordionGroup>
  <Accordion title="Security Considerations">
    * Limit MCP access to specific topics and actions
    * Use authentication for MCP server connections
    * Monitor MCP tool calls through logging
    * Implement rate limiting for MCP requests
  </Accordion>

  <Accordion title="Resource Management">
    * Configure appropriate timeouts for MCP operations
    * Limit concurrent MCP connections if needed
    * Monitor memory usage of MCP server processes
  </Accordion>

  <Accordion title="Error Handling">
    * Implement graceful fallbacks when the MCP server is unavailable
    * Log MCP communication errors for debugging
    * Set up alerts for repeated failures
  </Accordion>
</AccordionGroup>

***

## Troubleshooting

<AccordionGroup>
  <Accordion title="MCP Server Won't Start">
    * Verify SERVER\_COMMAND path is correct
    * Check SERVER\_ARGUMENTS syntax (comma-separated)
    * Ensure required packages are installed (npx, node, python)
    * Check system PATH includes required executables
  </Accordion>

  <Accordion title="Connection Timeout">
    * Verify MCP server is running and responsive
    * Check network/firewall settings
    * Increase timeout values if server startup is slow
    * Check server logs for errors
  </Accordion>

  <Accordion title="Tool Execution Fails">
    * Verify the requested tool is available
    * Check permissions for the operation
    * Review server logs for detailed error messages
    * Ensure broker has required access rights
  </Accordion>
</AccordionGroup>

***

## Next Steps

<CardGroup cols={2}>
  <Card title="REST API Routes" icon="globe" href="./rest-api-routes">
    Connect to external REST APIs.
  </Card>

  <Card title="Python Integration" icon="python" href="../actions/python-integration">
    Add custom AI/ML logic with Python.
  </Card>
</CardGroup>
