Skip to content

Your First MQTT Connection

Your First MQTT Connection

This tutorial walks you through establishing your first MQTT connection with mcmqtt, from basic pub/sub messaging to spawning your own brokers. Perfect for beginners and those new to MQTT.

Prerequisites

  • mcmqtt installed or accessible via uvx
  • Basic understanding of command-line interfaces
  • (Optional) MQTT client tools like mosquitto_pub/sub for testing

Step 1: Start mcmqtt

First, letโ€™s get mcmqtt running:

Terminal window
# Start mcmqtt in STDIO mode (default)
uvx mcmqtt
# Or in HTTP mode for web integration
uvx mcmqtt --transport http --port 8080

You should see output like:

๐Ÿš€ mcmqtt v2025.09.17 - FastMCP MQTT Server
โœ… Server started in STDIO mode
๐Ÿ“ก MQTT tools ready for MCP clients
๐Ÿ”ง Use 'mqtt_connect' to establish broker connections

Step 2: Connect to an MQTT Broker

Option A: Use an Existing Broker

If you have an MQTT broker running (like Mosquitto):

# In Claude Code or your MCP client, use the mqtt_connect tool:
mqtt_connect({
"host": "localhost",
"port": 1883,
"client_id": "my-first-client",
"keepalive": 60
})

Option B: Spawn a Broker with mcmqtt

mcmqtt can spawn a broker for you instantly:

# Spawn a broker on port 1884
spawn_mqtt_broker({
"port": 1884,
"config": {
"allow_anonymous": true,
"max_connections": 100,
"log_level": "info"
}
})

Then connect to your new broker:

mqtt_connect({
"host": "localhost",
"port": 1884,
"client_id": "my-spawned-broker-client"
})

Step 3: Subscribe to Topics

Now letโ€™s listen for messages on a topic:

# Subscribe to a simple topic
mqtt_subscribe({
"topic": "hello/world",
"qos": 1
})
# Subscribe to multiple topics with wildcards
mqtt_subscribe({
"topic": "sensors/+/temperature", # + matches one level
"qos": 0
})
mqtt_subscribe({
"topic": "events/#", # # matches multiple levels
"qos": 2
})

Understanding QoS Levels

  • QoS 0: At most once delivery (fire and forget)
  • QoS 1: At least once delivery (guaranteed delivery)
  • QoS 2: Exactly once delivery (guaranteed, no duplicates)

Step 4: Publish Your First Message

Send a message to other subscribers:

# Simple text message
mqtt_publish({
"topic": "hello/world",
"payload": "Hello from mcmqtt!",
"qos": 1,
"retain": false
})
# JSON payload with sensor data
mqtt_publish({
"topic": "sensors/living-room/temperature",
"payload": {
"value": 23.5,
"unit": "celsius",
"timestamp": "2024-01-15T10:30:00Z",
"sensor_id": "temp_001"
},
"qos": 1,
"retain": true # Retain for new subscribers
})

Step 5: Test Your Connection

Letโ€™s verify everything is working by testing with external tools:

Terminal window
# In a new terminal, test with mosquitto clients
# Subscribe to your topic
mosquitto_sub -h localhost -p 1884 -t "hello/world"
# Publish a test message
mosquitto_pub -h localhost -p 1884 -t "hello/world" -m "Test from command line"

You should see the message appear in both your mcmqtt logs and the mosquitto subscriber.

Step 6: Handle Connection Events

mcmqtt provides detailed connection status information:

# Check connection status
mqtt_get_status()
# Response will show:
{
"connected": true,
"broker": "localhost:1884",
"client_id": "my-spawned-broker-client",
"subscriptions": [
{"topic": "hello/world", "qos": 1},
{"topic": "sensors/+/temperature", "qos": 0}
],
"messages_sent": 5,
"messages_received": 12,
"uptime": "00:05:23"
}

Common Patterns

Request-Response Pattern

Implement request-response over MQTT:

# Client publishes request
mqtt_publish({
"topic": "requests/user-data",
"payload": {
"request_id": "req_001",
"user_id": "user123",
"reply_to": "responses/user-data/req_001"
}
})
# Subscribe to response
mqtt_subscribe({
"topic": "responses/user-data/req_001",
"qos": 1
})

Heartbeat Monitoring

Keep track of client health:

# Publish periodic heartbeat
mqtt_publish({
"topic": "heartbeat/my-client",
"payload": {
"timestamp": "2024-01-15T10:30:00Z",
"status": "healthy",
"memory_usage": "45%",
"cpu_usage": "12%"
},
"qos": 0,
"retain": true
})

Event Streaming

Stream real-time events:

# Stream application events
mqtt_publish({
"topic": "events/user-actions",
"payload": {
"event_type": "user_login",
"user_id": "user456",
"timestamp": "2024-01-15T10:30:00Z",
"metadata": {
"ip_address": "192.168.1.100",
"user_agent": "Mozilla/5.0..."
}
},
"qos": 1
})

Troubleshooting

Connection Refused

If you canโ€™t connect:

Terminal window
# Check if broker is running
netstat -an | grep :1883
# Check firewall settings
sudo ufw status
# Test basic connectivity
telnet localhost 1883

Messages Not Received

If subscriptions arenโ€™t working:

# Verify subscription was successful
mqtt_get_status()
# Check topic patterns match
# "sensors/+/temp" matches "sensors/room1/temp"
# but NOT "sensors/room1/humidity/temp"
# Verify QoS levels match publishing side

Performance Issues

For high-throughput scenarios:

# Increase connection limits
mqtt_connect({
"host": "localhost",
"port": 1883,
"client_id": "high-throughput-client",
"keepalive": 30,
"max_inflight_messages": 100,
"socket_options": {
"tcp_nodelay": true,
"buffer_size": 65536
}
})

Next Steps

Congratulations! Youโ€™ve successfully established your first MQTT connection. Hereโ€™s what to explore next:

๐Ÿ—๏ธ Build Agent Networks

Learn to coordinate multiple MQTT clients:

๐Ÿ“Š Real-time Data Processing

Process MQTT data streams effectively:

๐Ÿš€ Production Deployment

Scale your MQTT infrastructure:

๐Ÿ› ๏ธ Advanced Features

Explore mcmqttโ€™s advanced capabilities:


Youโ€™re now ready to build real-time, message-driven applications with mcmqtt! Start simple with basic pub/sub, then scale to sophisticated agent coordination patterns. ๐Ÿ“ก