Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/MotiaDev/motia/llms.txt

Use this file to discover all available pages before exploring further.

Engine Protocol

The iii Engine communicates with SDK workers via a JSON-based WebSocket protocol. All messages are sent as text frames (JSON) or binary frames (for telemetry).

Connection

WebSocket URL: ws://localhost:49134 (default) When a worker connects:
  1. Worker opens WebSocket connection
  2. Engine sends WorkerRegistered message with unique worker_id
  3. Worker can now send registration messages

Message Format

All messages have a type field (lowercase) that identifies the message type:
{
  "type": "registerfunction",
  "id": "math.add",
  "description": "Add two numbers"
}

Message Types

Worker Registration

WorkerRegistered

Direction: Engine → Worker Purpose: Confirms worker connection and provides worker ID
{
  "type": "workerregistered",
  "worker_id": "550e8400-e29b-41d4-a716-446655440000"
}
Fields:
  • worker_id (string): Unique identifier for this worker

Function Registration

RegisterFunction

Direction: Worker → Engine Purpose: Register a function that can be invoked
{
  "type": "registerfunction",
  "id": "math.add",
  "description": "Add two numbers",
  "request_format": {
    "type": "object",
    "properties": {
      "a": {"type": "number"},
      "b": {"type": "number"}
    }
  },
  "response_format": {
    "type": "object",
    "properties": {
      "sum": {"type": "number"}
    }
  },
  "metadata": {"version": "1.0"},
  "invocation": null
}
Fields:
  • id (string, required): Unique function identifier
  • description (string, optional): Human-readable description
  • request_format (object, optional): JSON Schema for input validation
  • response_format (object, optional): JSON Schema for output validation
  • metadata (object, optional): Custom metadata
  • invocation (HttpInvocationRef, optional): For external HTTP functions
HTTP Function Registration: For external HTTP endpoints, include invocation config:
{
  "type": "registerfunction",
  "id": "external.my_lambda",
  "description": "AWS Lambda function",
  "invocation": {
    "url": "https://api.example.com/lambda",
    "method": "POST",
    "timeout_ms": 30000,
    "headers": {"x-api-key": "secret"},
    "auth": {
      "type": "bearer",
      "token_key": "LAMBDA_TOKEN"
    }
  }
}

UnregisterFunction

Direction: Worker → Engine Purpose: Remove a previously registered function
{
  "type": "unregisterfunction",
  "id": "math.add"
}
Fields:
  • id (string, required): Function ID to unregister

Trigger Registration

RegisterTriggerType

Direction: Worker → Engine Purpose: Register a new trigger type (usually done by modules)
{
  "type": "registertriggertype",
  "id": "custom",
  "description": "Custom trigger type"
}
Fields:
  • id (string, required): Unique trigger type identifier
  • description (string, required): Human-readable description

RegisterTrigger

Direction: Worker → Engine Purpose: Register a trigger to invoke a function
{
  "type": "registertrigger",
  "id": "user-create-webhook",
  "trigger_type": "http",
  "function_id": "users.create",
  "config": {
    "api_path": "users",
    "http_method": "POST"
  }
}
Fields:
  • id (string, required): Unique trigger identifier
  • trigger_type (string, required): Type of trigger (e.g., http, queue, cron)
  • function_id (string, required): Function to invoke
  • config (object, required): Trigger-specific configuration
Common Trigger Configs: HTTP Trigger:
{
  "api_path": "users/:id",
  "http_method": "GET"
}
Queue Trigger:
{
  "topic": "orders.created"
}
Cron Trigger:
{
  "expression": "0 9 * * *"
}
State Trigger:
{
  "key_pattern": "user:*:status"
}

TriggerRegistrationResult

Direction: Worker → Engine Purpose: Confirm trigger registration (optional acknowledgment)
{
  "type": "triggerregistrationresult",
  "id": "user-create-webhook",
  "trigger_type": "http",
  "function_id": "users.create",
  "error": null
}
Fields:
  • id (string, required): Trigger ID
  • trigger_type (string, required): Trigger type
  • function_id (string, required): Associated function
  • error (ErrorBody, optional): Error details if registration failed

UnregisterTrigger

Direction: Worker → Engine Purpose: Remove a trigger
{
  "type": "unregistertrigger",
  "id": "user-create-webhook",
  "trigger_type": "http"
}
Fields:
  • id (string, required): Trigger ID to remove
  • trigger_type (string, optional): Trigger type (for optimization)

Function Invocation

InvokeFunction

Direction: Bidirectional (Engine ↔ Worker) Purpose: Request function execution
{
  "type": "invokefunction",
  "invocation_id": "a1b2c3d4-e5f6-4789-a012-3456789abcde",
  "function_id": "math.add",
  "data": {"a": 5, "b": 3},
  "traceparent": "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
  "baggage": "userId=alice,serverNode=DF:28"
}
Fields:
  • invocation_id (UUID, optional): Unique invocation ID for response tracking
  • function_id (string, required): Function to invoke
  • data (object, required): Input data for function
  • traceparent (string, optional): W3C trace context for distributed tracing
  • baggage (string, optional): W3C baggage for context propagation
Fire-and-Forget: Omit invocation_id for async execution without waiting for result.

InvocationResult

Direction: Bidirectional (Engine ↔ Worker) Purpose: Return function execution result
{
  "type": "invocationresult",
  "invocation_id": "a1b2c3d4-e5f6-4789-a012-3456789abcde",
  "function_id": "math.add",
  "result": {"sum": 8},
  "error": null,
  "traceparent": "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
  "baggage": "userId=alice,serverNode=DF:28"
}
Fields:
  • invocation_id (UUID, required): Matches the invoking message
  • function_id (string, required): Function that was invoked
  • result (any, optional): Success result (null if error)
  • error (ErrorBody, optional): Error details (null if success)
  • traceparent (string, optional): Trace context
  • baggage (string, optional): Baggage context
ErrorBody:
{
  "code": "validation_error",
  "message": "Invalid input: missing field 'a'"
}

Service Registration

RegisterService

Direction: Worker → Engine Purpose: Register a service (collection of functions)
{
  "type": "registerservice",
  "id": "payment-service",
  "name": "Payment Service",
  "description": "Handles payment processing"
}
Fields:
  • id (string, required): Unique service identifier
  • name (string, required): Service name
  • description (string, optional): Service description

Health & Keepalive

Ping

Direction: Bidirectional (Engine ↔ Worker) Purpose: Keepalive and connection health check
{
  "type": "ping"
}

Pong

Direction: Bidirectional (Engine ↔ Worker) Purpose: Response to Ping
{
  "type": "pong"
}

Binary Frames (Telemetry)

The engine accepts binary WebSocket frames with magic prefixes for telemetry:

OTLP Traces

Prefix: OTLP (4 bytes) Format: OTLP + JSON-encoded OpenTelemetry trace data
[0x4F, 0x54, 0x4C, 0x50] + JSON

Metrics

Prefix: MTRC (4 bytes) Format: MTRC + JSON-encoded OpenTelemetry metrics data
[0x4D, 0x54, 0x52, 0x43] + JSON

Logs

Prefix: LOGS (4 bytes) Format: LOGS + JSON-encoded OpenTelemetry logs data
[0x4C, 0x4F, 0x47, 0x53] + JSON

Trace Context Propagation

The engine supports W3C Trace Context for distributed tracing:

traceparent Format

00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
│  │                                │                  │
│  │                                │                  └─ flags
│  │                                └─ parent-id (16 hex)
│  └─ trace-id (32 hex)
└─ version

baggage Format

userId=alice,serverNode=DF:28,priority=high
Key-value pairs separated by commas.

Error Handling

Errors are returned in the error field of InvocationResult:
interface ErrorBody {
  code: string;     // Error code (e.g., "function_not_found")
  message: string;  // Human-readable error message
}
Common Error Codes:
  • function_not_found: Function ID doesn’t exist
  • invocation_error: General invocation error
  • validation_error: Input validation failed
  • timeout_error: Invocation timeout
  • serialization_error: JSON serialization failed

Example Flow

Complete Registration & Invocation

// 1. Worker connects
// <- {"type": "workerregistered", "worker_id": "..."}

// 2. Register function
// -> {"type": "registerfunction", "id": "math.add", ...}

// 3. Register HTTP trigger
// -> {"type": "registertrigger", "trigger_type": "http", "function_id": "math.add", ...}

// 4. HTTP request arrives at engine
// <- {"type": "invokefunction", "invocation_id": "...", "function_id": "math.add", "data": {...}}

// 5. Worker executes function
// -> {"type": "invocationresult", "invocation_id": "...", "result": {...}}

// 6. Engine returns HTTP response

Protocol Implementation

Location: src/protocol.rs All message types are defined as Rust enums with serde serialization:
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum Message {
    RegisterFunction { id: String, description: Option<String>, ... },
    InvokeFunction { invocation_id: Option<Uuid>, function_id: String, data: Value, ... },
    // ...
}

Next Steps

Build docs developers (and LLMs) love