Skip to main content
Glama
G1 UART MCP Server

G1 UART MCP Server

by danroblewis

G1 UART MCP Server

A Model Context Protocol (MCP) server that provides tools for communicating with G1 devices over Bluetooth Low Energy (BLE) using the Nordic UART protocol.

Overview

This project implements an MCP server that enables AI assistants and other MCP clients to:

  • Scan for G1 Bluetooth devices

  • Connect to G1 devices

  • Send and receive messages using the Nordic BLE UART protocol

  • Monitor connection status and device information

  • NEW: Automatically monitor and maintain stable connections

  • NEW: Auto-reconnect on connection loss

  • NEW: Configurable connection monitoring parameters

The server is particularly designed for working with Even G1 devices, which appear to be paired left/right devices for audio applications.

Related MCP server: BLE MCP Server

Features

  • Device Discovery: Scan for available G1 devices with automatic side detection (left/right)

  • BLE Connection Management: Connect, disconnect, and monitor connection status

  • Nordic UART Protocol: Full support for the Nordic UART service (6E400001-B5A3-F393-E0A9-E50E24DCCA9E)

  • Message Communication: Send hex-formatted messages and receive responses

  • MCP Integration: Seamless integration with MCP-compatible AI assistants and tools

  • 🆕 Connection Monitoring: Automatic heartbeat and health checks to maintain stable connections

  • 🆕 Auto-Reconnection: Automatically attempt to reconnect if the connection is lost

  • 🆕 Configurable Settings: Adjustable heartbeat intervals, timeouts, and reconnection parameters

Prerequisites

  • Python 3.8+

  • macOS (tested on darwin 24.3.0)

  • Bluetooth Low Energy support

  • Access to G1 devices

Installation

Run directly from GitHub without installation:

uvx --from git+https://github.com/danroblewis/g1_uart_mcp g1-device-mcp

For MCP Configuration: Add this to your mcp.json:

{
  "mcpServers": {
    "g1-device-mcp": {
      "command": "uvx",
      "args": [
        "--from",
        "git+https://github.com/danroblewis/g1_uart_mcp",
        "g1-device-mcp"
      ]
    }
  }
}

Option 2: Local Installation

  1. Clone the repository:

git clone <repository-url>
cd g1_uart_mcp
  1. Create a virtual environment:

python3 -m venv venv
source venv/bin/activate  # On macOS/Linux
  1. Install dependencies:

pip install -r requirements.txt

Configuration

The MCP server is configured via mcp.json. For the recommended uvx method, use this configuration:

{
  "mcpServers": {
    "g1-device-mcp": {
      "command": "uvx",
      "args": [
        "--from",
        "git+https://github.com/danroblewis/g1_uart_mcp",
        "g1-device-mcp"
      ]
    }
  }
}

Alternative: Local Installation If you prefer local installation, update the paths to match your system:

{
  "mcpServers": {
    "g1-device-mcp": {
      "command": "/path/to/your/venv/bin/python",
      "args": [
        "/path/to/your/g1_uart_mcp/mcp_server.py"
      ]
    }
  }
}

Usage

Starting the MCP Server

The server can be started directly or through an MCP client:

uvx --from git+https://github.com/danroblewis/g1_uart_mcp g1-device-mcp

Local Installation

python mcp_server.py

Available Tools

1. Scan for G1 Devices

scan_g1_devices()

Scans for available G1 devices and returns a list with device information including name, ID, side (left/right), and signal strength.

2. Connect to G1 Device

connect_g1_device(address)

Connects to a specific G1 device by its address or UUID.

3. Get Connection Status

get_g1_connection_status()

Returns detailed information about the current connection including device details, UART service availability, and connection monitoring statistics.

4. Send Message

send_g1_message(hex_data)

Sends a hex-formatted message to the connected device and waits for a response. Now includes automatic connection health checks and reconnection attempts.

5. Disconnect

disconnect_g1_device()

Disconnects from the currently connected device.

6. 🆕 Configure Connection Settings

configure_g1_connection_settings(
    heartbeat_interval=5.0,
    connection_timeout=30.0,
    auto_reconnect_enabled=True,
    max_reconnect_attempts=3,
    reconnect_delay=2.0
)

Configures connection monitoring and auto-reconnection parameters.

Example Workflow

  1. Scan for devices:

    devices = scan_g1_devices()
    # Returns list of available G1 devices
  2. Connect to a device:

    result = connect_g1_device("device_uuid_or_address")
  3. Configure connection monitoring (optional):

    configure_g1_connection_settings(
        heartbeat_interval=3.0,  # More frequent heartbeats
        auto_reconnect_enabled=True
    )
  4. Send a message:

    response = send_g1_message("2506")
    # Sends command 0x25 with data 0x06
    # Connection is automatically monitored and maintained
  5. Check status:

    status = get_g1_connection_status()
    # Now includes connection duration, last activity, and reconnection info
  6. Disconnect:

    disconnect_g1_device()

Connection Monitoring & Auto-Reconnection

How It Works

The enhanced MCP server now includes robust connection management:

  1. Heartbeat Monitoring: Sends periodic ping messages (every 5 seconds by default) to keep the connection alive

  2. Health Checks: Regularly verifies the connection is still responsive

  3. Auto-Detection: Automatically detects when the connection is lost

  4. Smart Reconnection: Attempts to reconnect up to 3 times with configurable delays

  5. Background Monitoring: All monitoring happens in the background without blocking message sending

Configuration Options

  • heartbeat_interval: How often to send heartbeat messages (default: 5 seconds)

  • connection_timeout: Maximum connection duration before health check (default: 30 seconds)

  • auto_reconnect_enabled: Whether to automatically attempt reconnection (default: True)

  • max_reconnect_attempts: Maximum number of reconnection attempts (default: 3)

  • reconnect_delay: Delay between reconnection attempts (default: 2 seconds)

Benefits

  • Stable Connections: Significantly reduces unexpected disconnections

  • Automatic Recovery: No manual intervention needed when connections drop

  • Better Reliability: Especially important for the critical send_g1_message command

  • Configurable: Adjust settings based on your specific use case and device behavior

Example Files

  • example_connect.py - Demonstrates device connection

  • example_scan.py - Shows device scanning functionality

  • example_send_message.py - Example of sending messages

  • example_tools.py - Comprehensive tool usage examples

  • 🆕 test_connection_monitoring.py - Demonstrates the new connection monitoring features

Architecture

Core Components

  • mcp_server.py: Main MCP server implementation with tool definitions and connection configuration

  • g1_uart_manager.py: Enhanced BLE UART protocol manager with connection monitoring and auto-reconnection

  • mcp.json: MCP server configuration

BLE UART Protocol

The server implements the Nordic UART service:

  • Service UUID: 6E400001-B5A3-F393-E0A9-E50E24DCCA9E

  • TX Characteristic: 6E400002-B5A3-F393-E0A9-E50E24DCCA9E (Write)

  • RX Characteristic: 6E400003-B5A3-F393-E0A9-E50E24DCCA9E (Notify)

Dependencies

  • mcp: Model Context Protocol implementation

  • bleak: Cross-platform Bluetooth Low Energy library

Troubleshooting

Common Issues

  1. Permission Denied: Ensure Bluetooth permissions are granted to your application

  2. Device Not Found: Verify the device is in range and discoverable

  3. Connection Failed: Check if the device is already connected to another client

  4. Message Timeout: Ensure the device is responsive and supports the Nordic UART protocol

  5. 🆕 Frequent Disconnections: Try adjusting connection monitoring settings or check device power management

Debug Mode

Enable debug logging by modifying the logging level in mcp_server.py:

logging.basicConfig(level=logging.DEBUG)

Connection Issues

If you're experiencing frequent disconnections:

  1. Check connection monitoring settings:

    status = get_g1_connection_status()
    print(f"Auto-reconnect: {status['auto_reconnect_enabled']}")
    print(f"Reconnect attempts: {status['reconnect_attempts']}")
  2. Adjust heartbeat frequency:

    configure_g1_connection_settings(heartbeat_interval=3.0)
  3. Increase reconnection attempts:

    configure_g1_connection_settings(max_reconnect_attempts=5)
  4. Check device power settings: Some devices may go to sleep mode, causing disconnections

Contributing

  1. Fork the repository

  2. Create a feature branch

  3. Make your changes

  4. Add tests if applicable

  5. Submit a pull request

License

[Add your license information here]

Support

For issues and questions, please create an issue or contact the maintainers.

Available Tools

5 tools
connect_g1_deviceA

Connect to a G1 device by address.

Args:
    address (str): The Bluetooth MAC address of the G1 device to connect to.
                  Format should be XX:XX:XX:XX:XX:XX where X are hexadecimal characters.
                  Example: "AA:BB:CC:DD:EE:FF"

Returns:
    Dict[str, Any]: JSON response with connection status including:
        - result: "success" or "error"
        - connected: Boolean indicating connection state
        - device_name: Name of connected device (if successful)
        - device_address: Address of connected device (if successful)
        - error: Error message if connection failed
    
Note:
    This establishes a BLE connection to the specified device and discovers
    the Nordic UART service and characteristics.

Inputs: address (required). Returns: result

disconnect_g1_deviceA

Disconnect from the current G1 device.

Returns:
    Dict[str, Any]: JSON response with disconnection status including:
        - result: "success" or "error"
        - disconnected: Boolean indicating disconnection state
        - device_name: Name of previously connected device (if successful)
        - error: Error message if disconnection failed
    
Note:
    This closes the BLE connection to the currently connected device,
    cleans up resources, stops the heartbeat mechanism, and resets connection state.

Inputs: no named parameters. Returns: result

get_g1_connection_statusA

Get current connection status and device info.

Returns:
    Dict[str, Any]: JSON response with detailed connection status including:
        - result: "success" or "error"
        - connected: Boolean indicating connection state
        - device_name: Name of connected device (if connected)
        - device_address: Address of connected device (if connected)
        - uart_service_available: Boolean indicating UART service availability
        - tx_characteristic_available: Boolean indicating TX characteristic availability
        - rx_characteristic_available: Boolean indicating RX characteristic availability
        - pending_messages_count: Number of pending messages
        - total_messages: Total message count
        - error: Error message if status check failed
    
Note:
    This returns detailed status information including:
     - Connection state (connected/disconnected)
     - Device name and address (if connected)
     - UART service availability
     - Number of pending messages
     - Total message count

Inputs: no named parameters. Returns: result

scan_g1_devicesA

Scan for available G1 devices.

Returns:
    Dict[str, Any]: JSON response with scan results including:
        - result: "success" or "error"
        - devices: List of discovered devices with their properties
        - count: Number of devices found
        - error: Error message if scan failed
    
Note:
    This performs an actual BLE scan for devices with names containing "G1_" pattern.
    Returns a structured list of discovered devices with their addresses and signal strength.

Inputs: no named parameters. Returns: result

send_g1_messageA

Send a message to the connected G1 device.

Args:
    hex_data (str): Hexadecimal string representation of the message to send.
                   Can contain spaces, tabs, or other whitespace which will be automatically removed.
                   Should contain only valid hexadecimal characters (0-9, A-F, a-f).
                   Examples: "2506", "25 06", "25 06 00 01", "25 06 00 01 04 02"

Returns:
    Dict[str, Any]: JSON response with message status including:
        - result: "success" or "error"
        - message_sent: Boolean indicating if message was sent
        - response_received: Boolean indicating if response was received
        - response_data: Response data in hex format (if received)
        - timeout: Boolean indicating if message timed out
        - error: Error message if sending failed
    
Note:
    This sends the hex_data as bytes to the connected G1 device using the
    Nordic BLE UART protocol and waits for a response up to 2 seconds.
    All messages are treated as commands and will timeout after 2 seconds if no response is received.
    Spaces, tabs, and other whitespace in hex_data are automatically removed before processing.
    
Examples:
    - send_g1_message("2506") -> Sends command 0x25 with data 0x06
    - send_g1_message("25 06") -> Same as above (spaces removed)
    - send_g1_message("25 06 00 01") -> Sends 0x25060001
    - send_g1_message("ABCD 1234") -> Sends 0xABCD1234
    - send_g1_message("1234567890ABCDEF") -> Sends longer message

Inputs: hex_data (required). Returns: result

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.4/5.0

    Scored across 5 tools

    Disambiguation5/5

    Each tool has a clearly distinct purpose with no overlap: connect, disconnect, get status, scan, and send message. The descriptions specify unique actions (e.g., connect_g1_device establishes a connection, while send_g1_device transmits data), making misselection unlikely. Tools are well-differentiated by their core functions within the G1 UART device management workflow.

    Naming Consistency5/5

    All tool names follow a consistent verb_noun pattern with 'g1_device' or 'g1_message' as the noun, using snake_case throughout (e.g., connect_g1_device, send_g1_message). The naming is predictable and uniform, enhancing readability and agent usability without any deviations in style or structure.

    Tool Count5/5

    With 5 tools, the server is well-scoped for managing G1 UART devices, covering essential operations like connection, disconnection, status checking, scanning, and message sending. Each tool serves a necessary role in the device lifecycle, avoiding bloat or gaps, making the count ideal for the domain's typical workflows.

    Completeness5/5

    The tool set provides complete coverage for G1 UART device management, including connection lifecycle (connect, disconnect, status), device discovery (scan), and data interaction (send message). There are no obvious gaps; agents can perform all core operations from scanning to communication without dead ends or missing critical functions.

    Maintenance

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      D
      maintenance
      A stateful Bluetooth Low Energy (BLE) MCP server that enables AI agents to scan, connect, read/write characteristics, and subscribe to notifications on BLE devices.
      35
      73 PyPI
      19
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables AI agents to control Bluetooth audio devices via MCP tools, including battery status, connect/disconnect, find-my, and snoop decoding.
      MIT
    • A
      license
      B
      quality
      C
      maintenance
      A lightweight Bluetooth Low Energy debug MCP server for AI agents. It provides 21 tools for BLE scanning, connection, GATT read/write, descriptor access, MTU query, notification subscription, device recon, and engine diagnostics.
      21
      Apache 2.0