Skip to main content
Glama
Benniu

emqx-mcp-server

by Benniu

publish_mqtt_message

Publish MQTT messages to EMQX clusters on EMQX Cloud or self-managed deployments for IoT and real-time communication applications.

Instructions

Publish an MQTT Message to Your EMQX Cluster on EMQX Cloud or Self-Managed Deployment

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
requestYes

Implementation Reference

  • MCP tool handler for 'publish_mqtt_message'. Extracts and validates parameters from the request (topic, payload, qos, retain), then delegates to EMQXClient.publish_message() to perform the publish.
    @mcp.tool(name="publish_mqtt_message", 
              description="Publish an MQTT Message to Your EMQX Cluster on EMQX Cloud or Self-Managed Deployment")
    async def publish(request):
        """Handle publish message request
        
        Args:
            request: MCP request containing message data
                - topic: MQTT topic 
                - payload: Message content
                - qos: Quality of Service (0, 1, or 2)
                - retain: Whether to retain the message (true or false)
        
        Returns:
            MCPResponse: Response object with publish result
        """
        self.logger.info("Handling publish request")
        
        # Extract parameters from the request
        topic = request.get("topic")
        payload = request.get("payload")
        qos = request.get("qos", 0)  # Default QoS level is 0
        retain = request.get("retain", False)  # Default is not to retain
        
        # Validate required parameters before proceeding
        if not topic:
            self.logger.error("Missing required parameter: topic")
            return f'"error": "Missing required parameter: topic"'
        
        if payload is None:
            self.logger.error("Missing required parameter: payload")
            return f'"error": "Missing required parameter: payload"'
        
        # Publish message to EMQX using the client
        result = await self.emqx_client.publish_message(
            topic=topic,
            payload=payload,
            qos=qos,
            retain=retain
        )
        
        self.logger.info(f"Message published successfully to topic: {topic}")
        return result
  • Instantiates EMQXMessageTools and calls its register_tools method on the FastMCP server instance, which defines and registers the 'publish_mqtt_message' tool using @mcp.tool decorator.
    emqx_message_tools = EMQXMessageTools(self.logger)
    emqx_message_tools.register_tools(self.mcp)
  • Supporting utility in EMQXClient class that makes the actual HTTP POST request to the EMQX broker's /publish API endpoint to publish the MQTT message.
    async def publish_message(self, topic: str, payload: str, qos: int=0, retain: bool=False):
        """
        Publish a message to an MQTT topic.
        
        Uses the EMQX HTTP API to publish a message to a specific MQTT topic.
        
        Args:
            topic (str): The MQTT topic to publish to
            payload (str): The message payload to publish
            qos (int, optional): Quality of Service level (0, 1, or 2). Defaults to 0.
            retain (bool, optional): Whether to retain the message. Defaults to False.
            
        Returns:
            dict: Response from the EMQX API or error information
        """
        url = f"{self.api_url}/publish"
        data = {
            "topic": topic,
            "payload": payload,
            "qos": qos,
            "retain": retain
        }
        self.logger.info(f"Publishing message to topic {topic}")
        async with httpx.AsyncClient() as client:
            try:
                response = await client.post(url, headers=self._get_auth_header(), json=data, timeout=30)
                response.raise_for_status()
                return self._handle_response(response)
            except Exception as e:
                self.logger.error(f"Error publishing message: {str(e)}")
                return {"error": str(e)}
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries full burden. It states the action ('Publish') which implies a write operation, but doesn't disclose behavioral traits like whether this requires authentication, what happens on failure, rate limits, or if messages are persistent. The description is minimal and lacks crucial operational context for a mutation tool.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that states the core purpose without unnecessary words. It's appropriately sized for a simple tool, though it could be more front-loaded with critical usage information. No wasted verbiage.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a mutation tool with no annotations, 0% schema coverage, and no output schema, the description is incomplete. It doesn't explain what the 'request' parameter should contain, what happens after publishing, potential error conditions, or return values. The agent lacks sufficient context to use this tool effectively.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must compensate. It mentions publishing a message but provides no information about the 'request' parameter - what format it should be in (JSON, string), what content it should contain, or examples. The description adds minimal value beyond the schema's structural definition.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('Publish') and resource ('MQTT Message') with specific deployment targets ('EMQX Cluster on EMQX Cloud or Self-Managed Deployment'). However, it doesn't explicitly distinguish this tool from its siblings (get_mqtt_client, kick_mqtt_client, list_mqtt_clients), which all operate on MQTT clients rather than messages. The purpose is clear but lacks sibling differentiation.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention prerequisites (e.g., needing an active MQTT connection), exclusions, or how it relates to the sibling tools. The deployment context is stated but doesn't help the agent decide when this tool is appropriate.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Benniu/emqx-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server