Skip to content

Latest commit

 

History

History
685 lines (479 loc) · 21.7 KB

File metadata and controls

685 lines (479 loc) · 21.7 KB

GABP 1.0 Specification

Version: 1.0
Status: Stable
Date: 2026-03-21

Abstract

The Game Agent Bridge Protocol (GABP) is a JSON-RPC-inspired protocol that enables communication between game modification frameworks and external automation tools. This specification defines the message format, core methods, error handling, and extensibility rules for GABP version 1.0.

1. Introduction

GABP enables communication between two types of programs:

  • Bridge: The client program that connects to a game mod (your AI tool or automation system)
  • Mod: The server program running inside a game (the game modification that exposes game functionality)

This protocol is designed for AI agents, testing frameworks, and other automation systems that need to interact with games. Common use cases include:

  • AI agents debugging game behavior during development
  • Automated testing of game features
  • AI-assisted game development and content creation
  • Remote game control for research and analysis

1.1 AI Agent Development Workflow

GABP supports AI agent development workflows similar to how human developers work:

  1. Game Launch: The bridge starts the game/application with the mod loaded
  2. Connection: Bridge establishes a secure connection to the game
  3. Discovery: Bridge discovers available game functionality through tools and resources
  4. Interaction: AI agent can read game state, execute actions, and monitor events
  5. Debugging: Real-time event monitoring and state inspection for debugging

This enables AI agents to verify code changes during development, just like human developers start applications to test their modifications.

2. Conformance

The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119.

3. Message Format

3.1 Envelope

All GABP messages are JSON objects that conform to a common envelope structure. A message MUST be a JSON object with the following properties:

  • v (string, required): Protocol version identifier. MUST be "gabp/1" for version 1.x
  • id (string, required): Unique identifier for the message, formatted as a UUID
  • type (string, required): Message type, one of "request", "response", or "event"

3.2 Request Messages

A request message has type of "request" and MUST include:

  • method (string, required): The method name being invoked
  • params (object, optional): Parameters for the method call

Request messages MUST NOT include result, error, channel, seq, or payload properties.

Example:

{
  "v": "gabp/1",
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "type": "request",
  "method": "tools/list",
  "params": {}
}

3.3 Response Messages

A response message has type of "response" and MUST include exactly one of:

  • result (any type): The successful result of the method call
  • error (object): Error information if the method call failed

Response messages MUST NOT include method, params, channel, seq, or payload properties.

The error object, when present, MUST contain:

  • code (integer, required): Numeric error code
  • message (string, required): Human-readable error description
  • data (any type, optional): Additional error-specific data

Example success:

{
  "v": "gabp/1",
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "type": "response",
  "result": {
    "status": "ok"
  }
}

Example error:

{
  "v": "gabp/1",
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "type": "response",
  "error": {
    "code": -32601,
    "message": "Method not found",
    "data": { "method": "unknown/method" }
  }
}

3.4 Event Messages

An event message has type of "event" and MUST include:

  • channel (string, required): Event channel name
  • seq (integer, required): Sequence number for the event (≥ 0)
  • payload (any type, required): Event data

Event messages MUST NOT include method, params, result, or error properties.

Example:

{
  "v": "gabp/1",
  "id": "550e8400-e29b-41d4-a716-446655440001",
  "type": "event",
  "channel": "player/move",
  "seq": 42,
  "payload": {
    "playerId": "steve",
    "position": { "x": 100, "y": 64, "z": 200 }
  }
}

4. Core Methods

GABP defines several core methods that compliant implementations SHOULD support:

4.1 Session Management

session/hello

Initiates a connection from bridge to mod.

Request Parameters:

  • token (string, required): Authentication token
  • bridgeVersion (string, required): Bridge software version
  • platform (string, required): Operating system ("windows", "macos", or "linux")
  • launchId (string, required): Unique identifier for this session

session/welcome

Response to session/hello indicating successful authentication.

Response Result:

  • agentId (string, required): Unique identifier for the mod instance
  • app (object, required): Application information
    • name (string, required): Game or application name
    • version (string, required): Game or application version
  • capabilities (object, required): Supported features (see capabilities schema)
  • schemaVersion (string, required): GABP schema version (pattern: ^1\.\d+(?:\.\d+)?$)

4.2 Tool Management

tools/list

Lists available tools/methods provided by the mod.

Request Parameters: None

Response Result:

  • tools (array, required): Array of tool objects (see tool schema)

tools/call

Invokes a specific tool with arguments.

Request Parameters:

  • name (string, required): Tool name to invoke
  • arguments (object, optional): Arguments for the tool

Response Result: Tool-specific result data

4.3 Event Management

events/subscribe

Subscribes to one or more event channels.

Request Parameters:

  • channels (array, required): Array of channel name strings

Response Result:

  • subscribed (array, required): Array of successfully subscribed channel names

events/unsubscribe

Unsubscribes from one or more event channels.

Request Parameters:

  • channels (array, required): Array of channel name strings

Response Result:

  • unsubscribed (array, required): Array of successfully unsubscribed channel names

4.4 Resource Management

resources/list

Lists available resources that can be read by the bridge.

Request Parameters:

  • pattern (string, optional): Glob pattern to filter resources (e.g., "world/", "config/.json")

Response Result:

  • resources (array, required): Array of resource objects, each containing:
    • uri (string, required): Resource URI
    • name (string, required): Human-readable resource name
    • description (string, optional): Description of the resource
    • mimeType (string, optional): MIME type hint
    • size (integer, optional): Size in bytes (for file resources)

resources/read

Reads the content of a specific resource.

Request Parameters:

  • uri (string, required): Resource URI to read

Response Result:

  • content (any type, required): Resource content (string for text, base64 for binary)
  • mimeType (string, optional): MIME type of the content
  • encoding (string, optional): Content encoding ("utf-8", "base64", etc.)

4.5 Game State Management

state/get

Gets the current game state or specific state components.

Request Parameters:

  • components (array, optional): Array of state component names to retrieve
  • playerId (string, optional): Player ID for player-specific state

Response Result:

  • state (object, required): Current game state data
  • timestamp (integer, required): Unix timestamp when state was captured

state/set

Sets or modifies game state (if supported by the game).

Request Parameters:

  • updates (object, required): State updates to apply
  • playerId (string, optional): Player ID for player-specific updates
  • validate (boolean, optional): Whether to validate updates before applying

Response Result:

  • applied (object, required): Successfully applied updates

4.6 Attention Management

Attention support is OPTIONAL and MUST be discovered through capabilities.methods and capabilities.events.

The attention surface is intended for important summarized game-side information that can invalidate an agent's assumptions or should otherwise affect execution ordering.

attention/current

Returns the current open attention item, if any.

Request Parameters: None

Response Result:

  • attention (object or null, required): The current attention item, or null when no attention item is open

attention/ack

Acknowledges a specific attention item explicitly.

Request Parameters:

  • attentionId (string, required): Stable attention identifier returned by attention/current, a lifecycle event, or another implementation-defined response that references the item

Response Result:

  • acknowledged (boolean, required): Whether the requested attention item was accepted as acknowledged
  • attentionId (string, required): The attention id that was requested
  • currentAttention (object or null, required): The currently open attention item after the ack attempt, or null when none remains open

4.7 Attention Event Channels

Implementations that support attention SHOULD expose lifecycle channels through capabilities.events.

Recommended canonical channels:

  • attention/opened
  • attention/updated
  • attention/cleared

These event channels all carry the same summarized attention object payload.

The bridge SHOULD treat asynchronous attention events as informative and low-latency, but SHOULD rely on its own execution gate or other implementation policy at the next game-bound decision point instead of assuming the host will immediately inject the event into active reasoning.

  • errors (array, optional): Array of validation or application errors

5. Method Names

Method names MUST follow the pattern ^[a-z]+(/[a-z]+)+$ (lowercase segments separated by forward slashes). The first segment typically represents a namespace or category.

Reserved method namespaces:

  • session/* - Session management
  • tools/* - Tool discovery and invocation
  • events/* - Event subscription management
  • resources/* - Resource access
  • state/* - Game state management

6. Error Codes

GABP uses JSON-RPC-compatible error codes:

  • -32600: Invalid Request - The JSON sent is not a valid request object
  • -32601: Method Not Found - The method does not exist or is not available
  • -32602: Invalid Params - Invalid method parameter(s)
  • -32603: Internal Error - Internal JSON-RPC error
  • -32000 to -32099: Server Error - Reserved for implementation-defined server errors

Custom error codes SHOULD use ranges outside of the JSON-RPC reserved ranges.

7. Extensibility

7.1 Custom Methods

Implementations MAY define custom methods beyond the core set. Custom method names MUST follow the naming pattern and SHOULD use implementation-specific namespaces to avoid conflicts.

7.2 Protocol Versioning

The protocol version gabp/1 allows for additive changes only:

  • New optional fields in existing messages
  • New methods
  • New error codes

Breaking changes require a new major version (e.g., gabp/2).

7.3 Capability Negotiation

Implementations MUST use the capabilities object in the session/welcome response to advertise supported features. Bridges SHOULD check capabilities before attempting to use optional features.

8. Message Ordering

  • Request-response pairs are matched by the id field
  • Multiple outstanding requests are allowed (asynchronous operation)
  • Events are delivered in sequence order per channel (using the seq field)
  • No ordering guarantees exist between different channels

9. Connection Lifecycle

  1. Establishment: Bridge establishes transport connection
  2. Authentication: Bridge sends session/hello with token
  3. Welcome: Mod responds with session/welcome and capabilities
  4. Operation: Normal request/response and event flow
  5. Termination: Either party may close the connection

10. Compliance

A compliant GABP implementation MUST:

  • Support the envelope format defined in Section 3
  • Implement the session/hello and session/welcome methods
  • Use the error codes defined in Section 6 for standard error conditions
  • Validate message structure according to the JSON schemas
  • Support at least one transport method (see transport.md)

A compliant implementation SHOULD:

  • Implement the core methods defined in Section 4
  • Support event subscriptions and delivery
  • Provide meaningful error messages
  • Implement proper capability negotiation

11. Security Considerations

See security.md for detailed security considerations including:

  • Token-based authentication
  • Transport security
  • Threat model analysis

12. AI Implementation Guide

This section provides compressed information and practical guidance specifically for AI assistants and automated tools building GABP-compliant implementations.

12.1 Protocol Summary for AI Context

Core Concept: GABP is a JSON-RPC-inspired protocol enabling AI tools (bridges) to communicate with game modifications (mods). Think of it as a standardized API for AI-game interaction.

Key Components:

  • Envelope: All messages are JSON with {"v":"gabp/1", "id":"uuid", "type":"request|response|event"}
  • Transport: stdio, TCP localhost, or named pipes with LSP-style headers
  • Auth: Shared token from config file, loopback-only connections
  • Methods: Namespaced like session/hello, tools/list, events/subscribe
  • Errors: JSON-RPC style with numeric codes (-32xxx for standard, -31xxx for custom)

Message Types:

  1. Request: {"type":"request", "method":"tools/list", "params":{}}
  2. Response: {"type":"response", "result":{} OR "error":{"code":-32601,"message":"..."}}
  3. Event: {"type":"event", "channel":"player/move", "seq":0, "payload":{}}

12.2 Building a GABP Bridge (Client)

When building an AI tool that connects to games, use this implementation template:

AI Prompt for Bridge Implementation

Create a GABP bridge client that:

1. TRANSPORT: Connect via stdio/TCP using LSP-style headers:
   "Content-Length: <bytes>\r\n\r\n{json}"

2. HANDSHAKE: Send session/hello with token from config file:
   {
     "v": "gabp/1",
     "id": "<uuid>",
     "type": "request",
     "method": "session/hello",
     "params": {
       "token": "<from-config>",
       "bridgeVersion": "1.0.0",
       "platform": "windows|macos|linux",
       "launchId": "unique-session-id"
     }
   }

3. CAPABILITIES: Parse session/welcome response to discover available tools/events:
   result.capabilities.methods = ["tools/list", "tools/call"]
   result.capabilities.events = ["player/move", "world/block_change"]

4. OPERATIONS:
   - Call tools: tools/call method with tool name and arguments
   - Subscribe to events: events/subscribe with channel names
   - Handle async events with proper sequencing

5. ERROR HANDLING: Check response.error field, map JSON-RPC codes to actions

Implementation requirements:
- Validate all messages against JSON schemas
- Handle connection drops gracefully
- Implement proper UUID generation
- Support concurrent request/response pairs
- Process events in sequence order per channel

Bridge Implementation Checklist

  • Transport Layer: Implement LSP framing for chosen transport (stdio/TCP/pipes)
  • Config Reader: Parse token from platform-specific config location
  • Message Validation: Validate outgoing requests and incoming responses
  • Session Management: Handle hello/welcome handshake and capability parsing
  • Request/Response: Support async request handling with UUID matching
  • Event Processing: Subscribe to channels and process events in sequence
  • Error Handling: Map error codes to appropriate bridge actions
  • Graceful Shutdown: Clean disconnect on session end

12.3 Building a GABP Mod (Server)

When building a game modification that exposes GABP functionality:

AI Prompt for Mod Implementation

Create a GABP mod server that:

1. TRANSPORT: Listen on stdio/TCP/pipe and parse LSP-framed messages

2. SESSION HANDLING: Respond to session/hello with capabilities:
   {
     "type": "response",
     "id": "<same-as-request>",
     "result": {
       "agentId": "my-game-mod-v1.0",
       "app": {"name": "MyGame", "version": "1.2.0"},
       "capabilities": {
         "methods": ["tools/list", "tools/call", "events/subscribe"],
         "events": ["player/move", "world/block_change"],
         "resources": ["gabp://game/world/schematic"]
       },
       "schemaVersion": "1.0"
     }
   }

3. TOOL REGISTRY: Implement tools/list and tools/call methods:
   - tools/list: Return available tools with schemas
   - tools/call: Execute tool and return result/error

4. EVENT SYSTEM: Implement events/subscribe and emit events:
   - Track subscribed channels per connection
   - Emit events with incrementing sequence numbers
   - Include game state in event payloads

5. RESOURCE ACCESS: Implement resources/list and resources/read:
   - Expose game data as URI-addressable resources
   - Support filtering and pagination

Game integration points:
- Hook into game's event system for real-time events
- Expose game APIs as GABP tools with proper input/output schemas
- Provide read/write access to game state through resources

Mod Implementation Checklist

  • Transport Server: Accept connections on chosen transport with LSP parsing
  • Token Validation: Verify tokens against bridge config file
  • Capability Declaration: Advertise available tools/events/resources accurately
  • Tool Implementation: Map GABP tools to actual game functionality
  • Event Broadcasting: Hook game events and broadcast to subscribed channels
  • Resource Exposure: Provide URI-based access to game data
  • State Management: Track per-connection subscriptions and session state
  • Schema Validation: Validate tool arguments and resource requests

12.4 Common Implementation Patterns

Message Validation Pattern

// Validate envelope structure for all messages
function validateGABPMessage(msg) {
  if (!msg.v || msg.v !== "gabp/1") throw new Error("Invalid version");
  if (!msg.id || !isValidUUID(msg.id)) throw new Error("Invalid ID");
  if (!["request", "response", "event"].includes(msg.type)) throw new Error("Invalid type");

  if (msg.type === "request" && !msg.method) throw new Error("Missing method");
  if (msg.type === "response" && !(msg.result || msg.error)) throw new Error("Missing result/error");
  if (msg.type === "event" && !(msg.channel && typeof msg.seq === "number")) throw new Error("Invalid event");
}

Error Response Pattern

// Standard error response format
function createErrorResponse(requestId, code, message, data = null) {
  return {
    v: "gabp/1",
    id: requestId,
    type: "response",
    error: {
      code: code, // Use standard JSON-RPC codes
      message: message, // Human-readable description
      data: data, // Optional additional context
    },
  };
}

Event Emission Pattern

// Emit events with proper sequencing
class EventEmitter {
  constructor() {
    this.sequences = new Map(); // channel -> seq number
    this.subscriptions = new Map(); // connection -> Set<channel>
  }

  emit(channel, payload) {
    const seq = this.sequences.get(channel) || 0;
    this.sequences.set(channel, seq + 1);

    const event = {
      v: "gabp/1",
      id: generateUUID(),
      type: "event",
      channel: channel,
      seq: seq,
      payload: payload,
    };

    // Send to all subscribers
    for (let [conn, channels] of this.subscriptions) {
      if (channels.has(channel)) {
        conn.send(event);
      }
    }
  }
}

12.5 Debugging and Testing

Debug Checklist

  • Message Logging: Log all sent/received messages with timestamps
  • Schema Validation: Validate against official JSON schemas in SCHEMA/1.0/
  • Conformance Tests: Test with examples in CONFORMANCE/1.0/valid/
  • Error Simulation: Test with invalid messages in CONFORMANCE/1.0/invalid/
  • Connection Handling: Test disconnect/reconnect scenarios
  • Concurrent Operations: Test multiple simultaneous requests
  • Event Ordering: Verify events arrive in sequence per channel

Integration Testing Pattern

// Basic integration test structure
async function testGABPIntegration() {
  // 1. Connect and handshake
  const bridge = new GABPBridge();
  await bridge.connect();
  const welcome = await bridge.hello(token);
  assert(welcome.capabilities);

  // 2. Test tool discovery and execution
  const tools = await bridge.listTools();
  assert(tools.length > 0);
  const result = await bridge.callTool(tools[0].name, {});
  assert(result !== undefined);

  // 3. Test event subscription
  const events = [];
  await bridge.subscribe(["test/channel"]);
  bridge.on("event", (e) => events.push(e));

  // Trigger event somehow...
  await sleep(100);
  assert(events.length > 0);
  assert(events[0].seq === 0);
}

12.6 Performance and Scaling Considerations

  • Connection Pooling: Bridge implementations should reuse connections when possible
  • Event Batching: Group related events to reduce message overhead
  • Resource Caching: Cache frequently-accessed resources to reduce mod load
  • Schema Caching: Cache and reuse parsed JSON schemas for validation
  • Connection Limits: Mods should limit concurrent connections to prevent DoS

13. References