MQTT-Mastra Integration Template

A production-ready template showcasing seamless MQTT integration with Mastra AI agents and tools. This template demonstrates how to build intelligent IoT systems that combine real-time MQTT messaging with AI-powered decision making.

🎯 Key Integration Features

MQTT + AI Agent Integration

  • πŸ“‘ Real-time MQTT Communication: Bi-directional messaging with any MQTT broker
  • πŸ€– AI-Powered Processing: Intelligent agents that respond to IoT data streams
  • πŸ”„ Auto-Memory Bridge: Automatic storage of MQTT messages in agent memory
  • πŸ› οΈ Modular Tool System: Reusable MQTT tools for any IoT use case
  • πŸ’Ύ Persistent Memory: SQLite-backed memory for historical data analysis
  • πŸ‘€ Human-in-the-Loop: Approval workflows for critical IoT actions

Technical Capabilities

  • MQTT Protocol Support: Full MQTT 3.1.1/5.0 with QoS levels
  • Topic Wildcards: Support for + and # wildcards in subscriptions
  • Connection Management: Auto-reconnect with exponential backoff
  • Message Bridge: Automatic MQTT β†’ Agent memory synchronization
  • Tool Composition: Chain multiple tools for complex IoT workflows

Prerequisites

  • Node.js >= 20.9.0
  • pnpm package manager
  • MQTT Broker (HiveMQ Cloud recommended - free tier available)
  • OpenAI API key (for AI agent functionality)

Quick Start

1. Clone the template

 1git clone <your-repo-url>
 2cd mqtt-mastra-template

2. Install dependencies

pnpm install

3. Configure environment

 1cp .env.example .env
 2# Edit .env with your MQTT broker details

Environment Requirements

Create a .env file based on .env.example:

 1# OpenAI API Key (optional, for voice features)
 2OPENAI_API_KEY=your-openai-api-key
 3
 4# =============================================================================
 5# MQTT BROKER CONFIGURATION
 6# =============================================================================
 7
 8HIVEMQ_BROKER_URL=your_hivemq_url
 9HIVEMQ_USERNAME=your_username
10HIVEMQ_PASSWORD=your_password

4. Start the application

  1. Start Mastra playground: pnpm run dev
  2. Open browser to playground URL
  3. Login to HiveMQ to simulate the IOT device messages

MQTT Integration Architecture

How It Works

  1. MQTT Messages arrive via broker subscriptions
  2. Memory Bridge automatically stores messages in shared memory
  3. AI Agent processes data using specialized tools
  4. Actions are executed via MQTT publish commands
  5. Human Approval required for critical operations

Example: Chicken Coop IoT Demo

The template includes a fully-functional chicken coop management system demonstrating:

  • Temperature monitoring with safety thresholds
  • Automated feeding schedules
  • Environmental control systems
  • Pattern detection from historical data

MQTT Tool Showcase

Connection Management

 1// Automatic connection with retry logic
 2await mqttConnectionTool.execute({ 
 3  action: 'connect',
 4  broker: process.env.HIVEMQ_BROKER_URL 
 5});

Subscribe with Memory Bridge

 1// Messages automatically stored in agent memory
 2await mqttSubscribeTool.execute({ 
 3  topic: 'sensors/+/temperature',
 4  qos: 1 
 5});

Intelligent Processing

 1// Agent analyzes MQTT data and takes action
 2if (temperature > threshold) {
 3  await agent.execute('Activate cooling systems');
 4}

Getting Started with MQTT Integration

Step 1: Configure Your MQTT Broker

Set up your MQTT connection in .env:

 1HIVEMQ_BROKER_URL=wss://your-cluster.hivemq.cloud:8884/mqtt
 2HIVEMQ_USERNAME=your-username
 3HIVEMQ_PASSWORD=your-password

Step 2: Launch Mastra Playground

 1pnpm dev
 2# Open http://localhost:3000 in your browser

Step 3: Test MQTT Integration

  1. Connect to Broker: Use the playground UI to establish MQTT connection
  2. Subscribe to Topics: Set up subscriptions like sensors/+/data
  3. Send Test Messages: Use your MQTT client to publish test data
  4. Watch AI Response: See the agent process and respond to MQTT messages

Step 4: Extend with Your Use Case

  1. Create Custom Tools: Build tools specific to your IoT devices
  2. Define Agent Logic: Customize agent instructions for your domain
  3. Add Workflows: Implement scheduled tasks and batch processing
  4. Scale Up: Deploy to production with environment-specific configs

MQTT Message Examples

Generic IoT Sensor Data

 1// Topic: sensors/{device-id}/telemetry
 2{
 3  "device_id": "sensor-001",
 4  "type": "temperature",
 5  "value": 72.5,
 6  "unit": "fahrenheit",
 7  "timestamp": "2024-01-15T10:00:00Z"
 8}

Command Messages

 1// Topic: devices/{device-id}/commands
 2{
 3  "command": "activate",
 4  "target": "cooling-system",
 5  "parameters": {
 6    "intensity": 75,
 7    "duration": 3600
 8  }
 9}

Status Updates

 1// Topic: devices/{device-id}/status
 2{
 3  "device_id": "actuator-001",
 4  "status": "online",
 5  "battery": 85,
 6  "last_action": "cooling_activated"
 7}

Resources & Documentation

Framework & Tools

IoT & MQTT Resources

Contributing

Contributions are welcome! Please feel free to submit pull requests or open issues for bugs, feature requests, or improvements.

By contributing to this project, you agree that your contributions will be licensed under the MIT License alongside the original project. Contributors retain copyright to their contributions and are added to the list of contributors.

License

This project is licensed under the MIT License - see below for details:

 1MIT License
 2
 3Copyright (c) 2024 Bruce Canedy and contributors
 4
 5Permission is hereby granted, free of charge, to any person obtaining a copy
 6of this software and associated documentation files (the "Software"), to deal
 7in the Software without restriction, including without limitation the rights
 8to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 9copies of the Software, and to permit persons to whom the Software is
10furnished to do so, subject to the following conditions:
11
12The above copyright notice and this permission notice shall be included in all
13copies or substantial portions of the Software.
14
15THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21SOFTWARE.

Attribution

When using this project, please provide attribution by:

  1. Including the copyright notice in your project
  2. Linking back to this repository
  3. Mentioning the use of the Mastra framework and HiveMQ for MQTT connectivity

Use Cases & Applications

This MQTT-Mastra integration template can be adapted for:

🏭 Industrial IoT

  • Equipment monitoring and predictive maintenance
  • Production line optimization
  • Quality control systems

🏠 Smart Home/Building

  • Environmental control systems
  • Security and access management
  • Energy optimization

🌾 Agriculture

  • Greenhouse automation
  • Irrigation control
  • Livestock monitoring

πŸ₯ Healthcare

  • Patient monitoring systems
  • Medical equipment management
  • Environmental compliance

πŸš— Transportation

  • Fleet management
  • Vehicle telemetry
  • Route optimization

Project Structure

 1src/mastra/
 2β”œβ”€β”€ index.ts                    # Mastra instance configuration
 3β”œβ”€β”€ agents/
 4β”‚   └── chicken-coop-agent.ts   # Example IoT agent implementation
 5└── tools/
 6    β”œβ”€β”€ mqtt/                    # Core MQTT Integration Tools
 7    β”‚   β”œβ”€β”€ mqtt-connection.ts   # Broker connection with auto-reconnect
 8    β”‚   β”œβ”€β”€ mqtt-subscribe.ts    # Topic subscription management
 9    β”‚   β”œβ”€β”€ mqtt-publish.ts      # Message publishing with QoS
10    β”‚   └── mqtt-memory-bridge.ts # Automatic MQTTβ†’Memory sync
11    β”œβ”€β”€ utils/                   # Reusable Utility Tools
12    β”‚   β”œβ”€β”€ shared-memory-tool.ts # Cross-tool data sharing
13    β”‚   β”œβ”€β”€ approval-request.ts  # Human-in-the-loop workflows
14    β”‚   └── log-event.ts         # Structured event logging
15    └── chicken-coop/            # Example Domain-Specific Tools
16        β”œβ”€β”€ coop-temp-alert.ts   # Temperature monitoring
17        β”œβ”€β”€ feed-schedule.ts     # Schedule management
18        β”œβ”€β”€ feeder-control.ts    # Device control via MQTT
19        └── coop-controls.ts     # Environmental systems

Building Your Own IoT Integration

1. Define Your MQTT Topics

 1const topics = [
 2  'sensors/+/temperature',  // Wildcard for all temperature sensors
 3  'devices/+/status',       // Device status updates
 4  'commands/+/execute'      // Command execution
 5];

2. Create Domain-Specific Tools

 1export const myCustomTool = createTool({
 2  id: 'my-custom-tool',
 3  description: 'Process IoT data for my use case',
 4  inputSchema: z.object({
 5    deviceId: z.string(),
 6    action: z.string()
 7  }),
 8  execute: async ({ deviceId, action }) => {
 9    // Your custom logic here
10  }
11});

3. Configure Your Agent

 1const myAgent = new Agent({
 2  name: 'My IoT Assistant',
 3  instructions: 'Monitor and control my IoT devices...',
 4  tools: {
 5    mqttConnect: mqttConnectionTool,
 6    mqttSubscribe: mqttSubscribeTool,
 7    myCustomTool: myCustomTool
 8  }
 9});