# MCP B4A

> MCP Server for B4A vibe coding development (just tested on Claude Code)

- **Type:** MCP server
- **Install:** `agentstack add mcp-unmateria-mcp-b4a`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [unmateria](https://agentstack.voostack.com/s/unmateria)
- **Installs:** 0
- **Category:** [Integrations](https://agentstack.voostack.com/c/integrations)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [unmateria](https://github.com/unmateria)
- **Source:** https://github.com/unmateria/MCP-B4A

## Install

```sh
agentstack add mcp-unmateria-mcp-b4a
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

**English** · [Español](README.es.md)

# MCP Server for B4A

Bridges [Claude Code](https://claude.ai/claude-code) (and any MCP-compatible client) with the [B4A](https://www.b4x.com/b4a.html) (Basic4Android) ecosystem.

Exposes 31 tools for compiling projects, reading/editing source modules, reading/modifying layouts, exploring libraries, deploying APKs, debugging via ADB, doing live visual UI verification directly on the device, and cleaning up sprite PNG artifacts — all without leaving your AI coding assistant.

---

## Tools

### Configuration

| Tool | Description |
|------|-------------|
| `b4a_get_config` | Returns current paths and config sources (auto-detected vs explicit) |
| `b4a_set_config` | Updates a configuration value |

### Build & Deploy

| Tool | Description |
|------|-------------|
| `b4a_build` | Compiles a B4A project via B4ABuilder.exe (release/debug/bundle) |
| `b4a_build_and_install` | Compiles **and** installs in one step — equivalent to `b4a_build` + `b4a_install_apk` |
| `b4a_get_build_log` | Returns the log from the last build |
| `b4a_get_signing_info` | Returns keystore path, alias, and signing status (passwords are never exposed) |
| `b4a_install_apk` | Installs an APK on a connected device via ADB |

### Project

| Tool | Description |
|------|-------------|
| `b4a_read_project` | Reads project metadata: libraries, modules, build configs |
| `b4a_list_project_files` | Lists source files, layouts, and assets |
| `b4a_project_context` | Single-call overview: app info, libraries, modules, and last build error |
| `b4a_list_recent_projects` | Lists recently opened projects from the B4A IDE history |

### Layouts

| Tool | Description |
|------|-------------|
| `b4a_read_layout` | Converts binary .bal/.bil to JSON |
| `b4a_write_layout` | Writes JSON back to .bal/.bil (with validation and backup) |
| `b4a_list_layouts` | Lists all layout files in a project directory |

### Libraries

| Tool | Description |
|------|-------------|
| `b4a_list_libraries` | Lists available B4A libraries with version info |
| `b4a_get_library_docs` | Returns formatted method/property/event documentation for a library |
| `b4a_search_library` | Searches across all library documentation |

### Source Modules

| Tool | Description |
|------|-------------|
| `b4a_read_bas` | Reads a `.bas` source module and returns its content with line numbers |
| `b4a_edit_bas` | Search-and-replace edit on a `.bas` file. Matches exact text (including indentation), normalises line endings, creates `.bak` backup. Rejects ambiguous matches unless `replace_all=true`. |

### Manifest

| Tool | Description |
|------|-------------|
| `b4a_read_manifest` | Extracts the Manifest Editor block from a .b4a file |
| `b4a_write_manifest` | Updates the Manifest Editor block |

### Device Interaction

Enables visual UI verification and device control without leaving Claude Code. Replaces the manual Bash + PIL screenshot workflow.

| Tool | Description |
|------|-------------|
| `b4a_screenshot` | Captures a PNG from the device. Optional `cropX/Y/W/H` for sub-regions, optional `delayMs` to wait before capture |
| `b4a_pixel_scan` | Reads RGB values from a saved PNG — individual points (`x,y` pairs) or a full region grid |
| `b4a_tap` | Sends a tap event at `(x, y)` device coordinates |
| `b4a_swipe` | Sends a swipe gesture from `(x1,y1)` to `(x2,y2)` with configurable duration |
| `b4a_launch_app` | Launches an installed app via `adb shell am start` |
| `b4a_key_event` | Sends an Android key event (BACK=4, HOME=3, MENU=82, ENTER=66, …) |
| `b4a_input_text` | Types text into the focused input field (spaces as `%s`) |

### Sprite Tools

| Tool | Description |
|------|-------------|
| `b4a_sprite_cleanup` | Cleans sprite PNG files generated by Gemini: removes white/gray border artifacts (residual dividing lines, anti-aliasing), optionally auto-crops transparent padding. Creates `.bak` backup before overwriting. Supports single file or `*.png` batch. **Use `autoCrop=false` for game sprites** — auto-crop changes canvas dimensions and deforms sprites when the game scales them to a fixed display size. |

### ADB / Debugging

| Tool | Description |
|------|-------------|
| `b4a_get_logcat` | Returns logcat output filtered by the B4A tag. Shows `[showing last N of M lines]` prefix when output is truncated. |
| `b4a_list_devices` | Lists connected ADB devices |

---

## Prerequisites

- [.NET 8 Runtime](https://dotnet.microsoft.com/download/dotnet/8.0) (or use the self-contained build)
- [B4A IDE](https://www.b4x.com/b4a.html) installed (required for compilation)
- [Android SDK Platform Tools](https://developer.android.com/tools/releases/platform-tools) (required for ADB tools)

---

## Installation

### 1. Get the binary

**Recommended — download the prebuilt executable:** grab `B4aMcp.exe` from the
[Releases page](https://github.com/unmateria/MCP-B4A/releases/latest). It is a
self-contained Windows build — no .NET runtime required.

**Alternative — build from source:**

```powershell
cd B4aMcp
dotnet publish -c Release -r win-x64 --self-contained -p:PublishSingleFile=true -o ../publish
```

### 2. Configure Claude Code

```bash
claude mcp add b4a C:\path\to\B4aMcp.exe
```

Or add manually to your MCP settings:

```json
{
  "mcpServers": {
    "b4a": {
      "command": "C:\\path\\to\\B4aMcp.exe",
      "args": []
    }
  }
}
```

### 3. First-time setup

Run `b4a_get_config` to check auto-detected paths. If B4A is installed in a non-standard location, configure manually:

```
b4a_set_config(key="b4aPath", value="C:\\B4A")
b4a_set_config(key="additionalLibrariesPath", value="C:\\B4A\\SharedLibs")
```

The server auto-detects paths from the B4A IDE settings file (`b4xV5.ini`) when possible. Config is stored at `%APPDATA%\mcp-b4a\config.json`.

---

## Layout Files (.bal / .bil)

B4A stores UI layouts in a proprietary binary format. This server includes a full port of the official [BalConverter](https://github.com/B4X-Community/B4X-BalConverter) to VB.NET, providing lossless binary-to-JSON roundtrip conversion.

- `.bal` — standard layout (Activity layouts)
- `.bil` — internal layout variant (RECT32/CNULL entries stripped on write)

**Roundtrip safety:** `b4a_write_layout` validates JSON structure and always creates a `.bak` backup before writing.

### EditText Required Properties

EditText controls in layout JSON require specific properties that differ from other control types. The B4A runtime does **not** null-guard all of them, so missing properties cause runtime crashes.

| Property | Type | Required | Default | Notes |
|----------|------|----------|---------|-------|
| `inputType` | string | Yes | — | `TEXT`, `NUMBERS`, `DECIMAL_NUMBERS`, `PHONE`, `NONE` |
| `password` | boolean | **Yes** | — | No null guard in B4A runtime — **crashes if missing** |
| `hint` | string | No | `""` | Placeholder text |
| `hintColor` | color | No | `0xFFF0F0F0` | Uses `ValueType: 6` format |
| `singleLine` | boolean | No | `true` | Text wrapping behavior |
| `wrap` | boolean | No | `true` | Has default in runtime |
| `forceDone` | boolean | No | `false` | Has default in runtime |

> **`inputType` values must be string constants, NOT integers.** B4A uses Java reflection (`getField("INPUT_TYPE_" + value)`) internally, so numeric values like `1` or `129` will crash at runtime with `NoSuchFieldException`.

`b4a_write_layout` automatically injects missing `password` and `singleLine` with safe defaults, and converts numeric `inputType` values to their named equivalents when possible. Warnings are included in the response.

---

## Common B4A Pitfall: DrawText Font Size is dp, Not Pixels

`Canvas.DrawText` in B4A interprets the font size parameter as **dp** (density-independent pixels). Android multiplies by `deviceDpi / 160` internally, so the same numeric font size renders at very different pixel sizes across devices. If UI containers (bitmaps, rects) use hardcoded pixel dimensions but fonts scale with DPI, **text will overflow on low-DPI devices**.

**Rule of thumb:** every UI dimension — container sizes, font sizes, positions, and touch zones — should be **proportional to `100%x` / `100%y`** (screen width/height in pixels). Never use hardcoded pixel values like `Dim btnW As Int = 200`.

See `b4a_language_gotchas` for more B4A-specific pitfalls.

---

## Notable Implementation Details

- **`b4a_build` WorkingDirectory**: `B4ABuilder.exe` is invoked with `WorkingDirectory = baseFolder`. Without this, the builder cannot locate the `.b4a` file even when `-BaseFolder` is passed, because it resolves the project filename against the current working directory of the calling process.

- **Manifest write safety**: `b4a_write_manifest` uses a `MatchEvaluator` lambda instead of a string replacement to prevent `Regex.Replace` from interpreting `$0`/`\1`-style backreferences in the manifest content. A `.bak` backup is always written before modifying the file.

- **Config resilience**: If `%APPDATA%\mcp-b4a\config.json` is malformed, the server falls back to an empty config and auto-detects paths from `b4xV5.ini` rather than crashing at startup.

---

## Security

- `b4a_build` only accepts paths to existing `.b4a` files — no arbitrary command execution.
- All file writes create `.bak` backups first.
- ADB tools that modify device state (`b4a_tap`, `b4a_swipe`, `b4a_launch_app`, `b4a_key_event`, `b4a_input_text`, `b4a_install_apk`) only interact with the connected Android device, not the host filesystem.
- Signing passwords from `b4xV5.ini` are never exposed through `b4a_get_signing_info`.

---

## Caching

The server caches results to avoid redundant I/O:

- **File-based cache** (mtime-invalidated): layout conversions, project parsing, library docs
- **TTL cache** (60s): device list, library listings
- **Simple store**: last build log (no expiry, replaced on each build)

Cache is invalidated automatically when source files change.

---

## Development

```powershell
cd B4aMcp
dotnet build
dotnet run
```

The server communicates via **stdio** (MCP standard). It does not open any network ports.

### Project Structure

```
B4aMcp/
├── Program.vb              # Server entry point
├── Models/
│   ├── B4aProject.vb       # Project metadata model
│   └── McpConfig.vb        # Configuration model
├── Tools/
│   ├── AdbTools.vb          # logcat, devices, install APK
│   ├── BuildTools.vb        # compile, build+install combo, build log, signing info
│   ├── ConfigTools.vb       # get/set configuration
│   ├── DeviceTools.vb       # screenshot, tap, swipe, launch app, pixel scan, key event, input text
│   ├── LayoutTools.vb       # read/write/list layouts + EditText validation
│   ├── LibraryTools.vb      # list, docs, search libraries
│   ├── BasTools.vb           # read/edit .bas source modules
│   ├── ManifestTools.vb     # read/write manifest block
│   ├── ProjectTools.vb      # project metadata, file listing, context
│   └── SpriteTools.vb       # sprite PNG cleanup: edge artifact removal + auto-crop
└── Utils/
    ├── AppConfig.vb          # Config management + B4A IDE auto-detection
    ├── B4aParser.vb          # .b4a project file parser
    ├── BalConverter.vb        # Binary .bal/.bil ↔ JSON converter
    └── CacheManager.vb       # Mtime-based + TTL caching
```

### Tech Stack

- **VB.NET** targeting **.NET 8**
- [ModelContextProtocol](https://www.nuget.org/packages/ModelContextProtocol) SDK (0.9.0-preview.2)
- [Newtonsoft.Json](https://www.nuget.org/packages/Newtonsoft.Json) for serialization
- [System.Drawing.Common](https://www.nuget.org/packages/System.Drawing.Common) for PNG pixel reading (Windows only)

---

## License

MIT

## Source & license

This open-source MCP server is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [unmateria](https://github.com/unmateria)
- **Source:** [unmateria/MCP-B4A](https://github.com/unmateria/MCP-B4A)
- **License:** MIT

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** no
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** no
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/mcp-unmateria-mcp-b4a
- Seller: https://agentstack.voostack.com/s/unmateria
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
