Skip to main content
Glama

mgba_read16

Retrieve a 16-bit unsigned little-endian value from a 2-byte aligned GBA memory address.

Instructions

Read an unsigned 16-bit little-endian value from a GBA memory address. Address should be 2-byte aligned.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
addressYesGBA memory address (must be 2-byte aligned)

Implementation Reference

  • Tool definition (schema) for 'mgba_read16': declares name, description, and inputSchema requiring an integer 'address' (2-byte aligned).
    {
      name: "mgba_read16",
      description: "Read an unsigned 16-bit little-endian value from a GBA memory address. Address should be 2-byte aligned.",
      inputSchema: {
        type: "object",
        required: ["address"],
        properties: {
          address: { type: "integer", description: "GBA memory address (must be 2-byte aligned)" },
        },
      },
    },
  • Handler for 'mgba_read16': calls mgba.call<number>('read16', { address }) and returns formatted hex result.
    case "mgba_read16": {
      const v = await mgba.call<number>("read16", { address: p.address });
      return ok(`0x${(p.address as number).toString(16).toUpperCase()}: ${formatHex(v)}`);
    }
  • src/tools.ts:258-411 (registration)
    Registration function 'registerTools' that sets up both ListToolsRequestSchema (which includes the TOOLS array with mgba_read16) and CallToolRequestSchema (which dispatches to the mgba_read16 handler case).
    export function registerTools(server: Server, mgba: MgbaClient): void {
      server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
    
      server.setRequestHandler(CallToolRequestSchema, async (req) => {
        const { name, arguments: args = {} } = req.params;
        const p = args as Record<string, unknown>;
    
        switch (name) {
          case "mgba_ping": {
            const r = await mgba.call<string>("ping");
            return ok(r);
          }
    
          case "mgba_get_info": {
            const r = await mgba.call<{
              title?: string;
              code?: string;
              frame?: number;
              platform?: number | string;
              capabilities?: Record<string, boolean>;
            }>("get_info");
            const lines = [
              `Title:    ${r.title ?? "(unavailable)"}`,
              `Code:     ${r.code ?? "(unavailable)"}`,
              `Platform: ${r.platform ?? "(unavailable)"}`,
              `Frame:    ${r.frame ?? "(unavailable)"}`,
            ];
            if (r.capabilities) {
              const present = Object.entries(r.capabilities).filter(([, v]) => v).map(([k]) => k);
              const missing = Object.entries(r.capabilities).filter(([, v]) => !v).map(([k]) => k);
              lines.push("");
              lines.push(`Capabilities present: ${present.length ? present.join(", ") : "(none)"}`);
              if (missing.length) lines.push(`Missing on this build: ${missing.join(", ")}`);
            }
            return ok(lines.join("\n"));
          }
    
          case "mgba_read8": {
            const v = await mgba.call<number>("read8", { address: p.address });
            return ok(`0x${(p.address as number).toString(16).toUpperCase()}: ${formatHex(v)}`);
          }
    
          case "mgba_read16": {
            const v = await mgba.call<number>("read16", { address: p.address });
            return ok(`0x${(p.address as number).toString(16).toUpperCase()}: ${formatHex(v)}`);
          }
    
          case "mgba_read32": {
            const v = await mgba.call<number>("read32", { address: p.address });
            return ok(`0x${(p.address as number).toString(16).toUpperCase()}: ${formatHex(v)}`);
          }
    
          case "mgba_write8": {
            await mgba.call("write8", { address: p.address, value: p.value });
            return ok(`Wrote ${formatHex(p.value)} → 0x${(p.address as number).toString(16).toUpperCase()}`);
          }
    
          case "mgba_write16": {
            await mgba.call("write16", { address: p.address, value: p.value });
            return ok(`Wrote ${formatHex(p.value)} → 0x${(p.address as number).toString(16).toUpperCase()}`);
          }
    
          case "mgba_write32": {
            await mgba.call("write32", { address: p.address, value: p.value });
            return ok(`Wrote ${formatHex(p.value)} → 0x${(p.address as number).toString(16).toUpperCase()}`);
          }
    
          case "mgba_read_range": {
            const bytes = await mgba.call<number[]>("read_range", {
              address: p.address,
              length:  p.length,
            });
            const hex = bytes
              .map((b) => b.toString(16).padStart(2, "0").toUpperCase())
              .join(" ");
            const addr = (p.address as number).toString(16).toUpperCase();
            return ok(`0x${addr} [${bytes.length} bytes]:\n${hex}`);
          }
    
          case "mgba_write_range": {
            const r = await mgba.call<{ written: number }>("write_range", {
              address: p.address,
              bytes:   p.bytes,
            });
            const addr = (p.address as number).toString(16).toUpperCase();
            return ok(`Wrote ${r.written} bytes → 0x${addr}`);
          }
    
          case "mgba_press_buttons": {
            const r = await mgba.call<{ queued: boolean; queue_size: number }>("press_buttons", {
              buttons:        p.buttons,
              frames:         p.frames         ?? 1,
              release_frames: p.release_frames ?? 1,
            });
            const keys = (p.buttons as string[]).join("+");
            return ok(
              `Queued press: ${keys} ` +
              `(hold ${p.frames ?? 1}f, release ${p.release_frames ?? 1}f). ` +
              `Queue size: ${r.queue_size}`,
            );
          }
    
          case "mgba_advance_frames": {
            const frame = await mgba.call<number>("advance_frames", { count: p.count ?? 1 });
            return ok(`Advanced ${p.count ?? 1} frame(s). Current frame: ${frame}`);
          }
    
          case "mgba_pause": {
            await mgba.call("pause");
            return ok("Emulation paused");
          }
    
          case "mgba_unpause": {
            await mgba.call("unpause");
            return ok("Emulation resumed");
          }
    
          case "mgba_reset": {
            await mgba.call("reset");
            return ok("ROM reset");
          }
    
          case "mgba_screenshot": {
            const path = await mgba.call<string>("screenshot", p.path ? { path: p.path } : {});
            return ok(`Screenshot saved: ${path}`);
          }
    
          case "mgba_save_state": {
            if (p.slot === undefined && p.path === undefined) {
              throw new Error("provide either `slot` (0-9) or `path`");
            }
            const r = await mgba.call<{ slot?: number; path?: string }>("save_state", {
              ...(p.slot !== undefined ? { slot: p.slot } : {}),
              ...(p.path !== undefined ? { path: p.path } : {}),
            });
            return ok(r.path ? `Saved state to ${r.path}` : `Saved state to slot ${r.slot}`);
          }
    
          case "mgba_load_state": {
            if (p.slot === undefined && p.path === undefined) {
              throw new Error("provide either `slot` (0-9) or `path`");
            }
            const r = await mgba.call<{ slot?: number; path?: string }>("load_state", {
              ...(p.slot !== undefined ? { slot: p.slot } : {}),
              ...(p.path !== undefined ? { path: p.path } : {}),
            });
            return ok(r.path ? `Loaded state from ${r.path}` : `Loaded state from slot ${r.slot}`);
          }
    
          default:
            throw new Error(`Unknown tool: ${name}`);
        }
      });
    }
  • Helper functions 'ok' (format success response) and 'formatHex' (format number as decimal + hex) used by the mgba_read16 handler.
    function ok(text: string) {
      return { content: [{ type: "text" as const, text }] };
    }
    
    function formatHex(n: unknown): string {
      if (typeof n !== "number") return String(n);
      return `${n} (0x${n.toString(16).toUpperCase()})`;
    }
  • MgbaClient.call() — the generic RPC method that the mgba_read16 handler uses to send the 'read16' RPC call to the mGBA Lua bridge over TCP.
    async call<T = unknown>(
      method: string,
      params?: Record<string, unknown>,
    ): Promise<T> {
      // Lazy (re)connect — bridge.lua reloads kill the socket, and the user
      // shouldn't have to restart the MCP host every time they edit the script.
      if (!this.socket || this.socket.destroyed) {
        try {
          await this.connect();
        } catch (err) {
          throw new Error(
            `Cannot reach mGBA bridge at ${this.host}:${this.port}. ` +
            `Make sure mGBA is running with bridge.lua loaded (Tools > Scripting). ` +
            `Underlying error: ${(err as Error).message}`,
          );
        }
      }
    
      return new Promise<T>((resolve, reject) => {
        const sock = this.socket;
        if (!sock) {
          reject(new Error("socket vanished after connect"));
          return;
        }
    
        const id = this.nextId++;
        this.pending.set(id, (resp) => {
          if (resp.error) {
            reject(new Error(`mGBA RPC error [${resp.error.code}]: ${resp.error.message}`));
          } else {
            resolve(resp.result as T);
          }
        });
    
        const msg = JSON.stringify({ id, method, params: params ?? {} }) + "\n";
        sock.write(msg, (err) => {
          if (err) {
            this.pending.delete(id);
            reject(err);
          }
        });
      });
    }
Behavior4/5

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

Discloses the 2-byte alignment constraint, which is beyond the schema and crucial for correct invocation. No annotations exist, so the description carries the burden well.

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?

Two concise sentences, front-loaded with the primary action and followed by a critical constraint. No wasted words.

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

Completeness4/5

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

Coverage is adequate for a low-complexity tool: states input, alignment, and output type. Lacks error behavior details but suffices for distinguishing among siblings.

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

Parameters4/5

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

Adds meaning beyond the schema by explaining the output type and endianness. Schema only describes the parameter as an integer; description clarifies the value's nature.

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

Purpose5/5

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

Explicitly states it reads an unsigned 16-bit little-endian value from GBA memory, distinguishing it from siblings like mgba_read8 and mgba_read32. The verb 'read' and resource 'GBA memory address' are clear.

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

Usage Guidelines3/5

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

Implicitly indicates usage for reading 16-bit little-endian values, but lacks explicit guidance on when not to use it (e.g., for signed values or different endianness) or alternatives.

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/dmang-dev/mcp-mgba'

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