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
- Start Mastra playground:
pnpm run dev
- Open browser to playground URL
- Login to HiveMQ to simulate the IOT device messages
MQTT Integration Architecture
How It Works
- MQTT Messages arrive via broker subscriptions
- Memory Bridge automatically stores messages in shared memory
- AI Agent processes data using specialized tools
- Actions are executed via MQTT publish commands
- 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
- Connect to Broker: Use the playground UI to establish MQTT connection
- Subscribe to Topics: Set up subscriptions like
sensors/+/data
- Send Test Messages: Use your MQTT client to publish test data
- Watch AI Response: See the agent process and respond to MQTT messages
Step 4: Extend with Your Use Case
- Create Custom Tools: Build tools specific to your IoT devices
- Define Agent Logic: Customize agent instructions for your domain
- Add Workflows: Implement scheduled tasks and batch processing
- 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
-
Mastra AI Framework - Core framework for building AI agents and workflows
-
HiveMQ Cloud - MQTT broker for IoT communication
-
OpenAI API - AI models for agent intelligence
IoT & MQTT Resources
- MQTT Protocol - Lightweight messaging protocol for IoT
- Node.js MQTT Client - JavaScript client library
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:
- Including the copyright notice in your project
- Linking back to this repository
- 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});