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/subfor testing
Step 1: Start mcmqtt
First, letโs get mcmqtt running:
# Start mcmqtt in STDIO mode (default)uvx mcmqtt
# Or in HTTP mode for web integrationuvx mcmqtt --transport http --port 8080You 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 connectionsStep 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 1884spawn_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 topicmqtt_subscribe({ "topic": "hello/world", "qos": 1})
# Subscribe to multiple topics with wildcardsmqtt_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 messagemqtt_publish({ "topic": "hello/world", "payload": "Hello from mcmqtt!", "qos": 1, "retain": false})
# JSON payload with sensor datamqtt_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:
# In a new terminal, test with mosquitto clients# Subscribe to your topicmosquitto_sub -h localhost -p 1884 -t "hello/world"
# Publish a test messagemosquitto_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 statusmqtt_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 requestmqtt_publish({ "topic": "requests/user-data", "payload": { "request_id": "req_001", "user_id": "user123", "reply_to": "responses/user-data/req_001" }})
# Subscribe to responsemqtt_subscribe({ "topic": "responses/user-data/req_001", "qos": 1})Heartbeat Monitoring
Keep track of client health:
# Publish periodic heartbeatmqtt_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 eventsmqtt_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:
# Check if broker is runningnetstat -an | grep :1883
# Check firewall settingssudo ufw status
# Test basic connectivitytelnet localhost 1883Messages Not Received
If subscriptions arenโt working:
# Verify subscription was successfulmqtt_get_status()
# Check topic patterns match# "sensors/+/temp" matches "sensors/room1/temp"# but NOT "sensors/room1/humidity/temp"
# Verify QoS levels match publishing sidePerformance Issues
For high-throughput scenarios:
# Increase connection limitsmqtt_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:
- Building Agent Networks - Multi-client coordination patterns
๐ Real-time Data Processing
Process MQTT data streams effectively:
- Real-time Data Streams - Stream processing and analytics
๐ Production Deployment
Scale your MQTT infrastructure:
- Production Deployment - High-availability and performance tuning
๐ ๏ธ Advanced Features
Explore mcmqttโs advanced capabilities:
- Custom Tools - Extend mcmqtt with your own tools
- Monitoring - Set up comprehensive observability
- Broker Management - Advanced broker configuration
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. ๐ก