Skip to main content
Glama

send_data

Send data to a serial port using text (UTF-8) or binary (Base64) format for direct device communication.

Instructions

向已打开的串口发送数据,支持文本和二进制模式

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
portYes串口路径,如 /dev/ttyUSB0 或 COM1
dataYes要发送的数据(文本为UTF-8,二进制为Base64)
is_binaryNo是否为二进制模式,True 时 data 为 Base64 编码

Implementation Reference

  • The main send_data handler function. Takes port, data, and is_binary parameters. Decodes data (base64 if binary, UTF-8 otherwise) and delegates to serial_manager.send_data().
    def send_data(
        port: str,
        data: str,
        is_binary: bool = False,
    ) -> dict[str, Any]:
        """发送数据到串口
    
        Args:
            port: 串口路径
            data: 要发送的数据(文本模式为 UTF-8 字符串,二进制模式为 Base64 编码)
            is_binary: 是否为二进制模式
    
        Returns:
            发送结果,包含发送的字节数
        """
        manager = get_serial_manager()
    
        # 编码转换
        if is_binary:
            try:
                raw_data = base64.b64decode(data)
            except Exception as e:
                raise InvalidParamError("data", data, f"Base64 解码失败:{e}")
        else:
            raw_data = data.encode("utf-8")
    
        bytes_written = manager.send_data(port, raw_data)
        return {"success": True, "bytes_written": bytes_written}
  • SerialManager.send_data() - low-level helper that writes raw bytes to the serial port via pyserial.
    def send_data(self, port: str, data: bytes) -> int:
        """发送原始字节数据
    
        Args:
            port: 串口路径
            data: 要发送的字节数据
    
        Returns:
            发送的字节数
    
        Raises:
            PortClosedError: 串口未打开
            WriteFailedError: 写入失败
        """
        with self._lock:
            if port not in self._ports:
                raise PortClosedError(port)
    
            managed = self._ports[port]
            try:
                result = managed.serial.write(data)
                bytes_written: int = result if result is not None else 0
                logger.debug("发送数据到串口 %s:%d 字节", port, bytes_written)
                return bytes_written
            except SerialException as e:
                logger.error("串口写入失败:%s - %s", port, e)
                raise WriteFailedError(port, str(e)) from e
  • SEND_DATA_TOOL dictionary defining name, description, and JSON Schema inputSchema (port, data required; is_binary optional boolean).
    SEND_DATA_TOOL: dict[str, Any] = {
        "name": "send_data",
        "description": "向已打开的串口发送数据,支持文本和二进制模式",
        "inputSchema": {
            "type": "object",
            "properties": {
                "port": {
                    "type": "string",
                    "description": "串口路径,如 /dev/ttyUSB0 或 COM1",
                },
                "data": {
                    "type": "string",
                    "description": "要发送的数据(文本为UTF-8,二进制为Base64)",
                },
                "is_binary": {
                    "type": "boolean",
                    "description": "是否为二进制模式,True 时 data 为 Base64 编码",
                    "default": False,
                },
            },
            "required": ["port", "data"],
        },
    }
  • Registration of send_data tool in handle_list_tools(), listing it in the tool enumeration.
    types.Tool(
        name=SEND_DATA_TOOL["name"],
        description=SEND_DATA_TOOL["description"],
        inputSchema=SEND_DATA_TOOL["inputSchema"],
    ),
  • Dispatch of send_data calls in handle_call_tool() - routes the 'send_data' tool name to the send_data function.
    elif name == "send_data":
        result = send_data(**arguments)
Behavior2/5

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

With no annotations, the description only implies the port must be open, but fails to disclose side effects, success/failure behavior, or state changes beyond sending.

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

Conciseness5/5

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

A single, clear sentence with zero wasted words. Efficiently conveys core purpose and mode support.

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

Completeness3/5

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

No output schema exists. The description covers basic operation but omits return value or error behavior, leaving the agent uncertain about outcome.

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

Parameters3/5

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

Schema coverage is 100% with descriptions for all params. The description adds 'text is UTF-8' (not in schema) but overall adds marginal value beyond schema.

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 tool sends data to an opened serial port with text/binary modes, using specific verb and resource. It distinguishes from siblings like read_data but does not explicitly contrast.

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 gives no guidance on when to use this tool vs alternatives (e.g., send_command), nor any prerequisites or exclusions.

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/donnel666/uart-mcp'

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