📋 D6e Docker Stf Development

This skill helps you build Docker-based State Transition Functions for D6E to process data, access internal SQL APIs, and output JSON.

QUICK INSTALL
npx playbooks add skill d6e-ai/d6e-docker-stf-skills --skill d6e-docker-stf-development

D6e Docker Stf Development instructions

D6E Docker STF Development

Overview

Docker STFs are containerized applications that execute as workflow steps in D6E. They read JSON from stdin, process data with custom logic, access workspace databases via internal API, and output JSON to stdout.

References

Focused guides (read before calling d6e APIs from a container):

| Topic | Doc |
|-------|-----|
| sources = input steps only — not $steps[n] / prior STF output | [references/stdin-sources-vs-steps.md](references/stdin-sources-vs-steps.md) |
| Instant-run / describe vs workflow — User vs Stf SQL policies, caller: null | [references/instant-run-vs-production.md](references/instant-run-vs-production.md) |
| POLICY_DENIED, DDL_FORBIDDEN, 23-char tables, uuidv7(), modql | [references/sql-errors-and-policy.md](references/sql-errors-and-policy.md) |
| api_token is SQL-only — not saas-proxy, files, or downloads | [references/external-apis.md](references/external-apis.md) |
| Concurrency queue, 5 min timeout, 10 MB stdout, stdin OOM, secret_keys | [references/limits-and-timeouts.md](references/limits-and-timeouts.md) |
| Binary files via workflow File input sources (base64 in sources) | [references/storage-and-files.md](references/storage-and-files.md) |
| Full API schemas and language templates | [reference.md](reference.md) |
| Additional patterns and examples | [examples.md](examples.md) |

When to Use

Apply this skill when users request:

  • "Create a D6E Docker STF that..."
  • "Build a custom STF for D6E that..."
  • "I need a Docker-based workflow step..."
  • "Help me create a data processing function for D6E"

Core Concepts

Input Format

Docker STFs receive this JSON via stdin:

{
  "workspace_id": "UUID",
  "stf_id": "UUID",
  "caller": "UUID | null",
  "api_url": "http://host.docker.internal:8080",
  "api_token": "<signed short-lived token generated per execution>",
  "input": {
    "operation": "...",
    ...user-defined parameters
  },
  "sources": {
    "step_name": <resolved input step value>
  }
}

Notes:

  • api_url points back at the d6e API from inside the container. The

default is http://host.docker.internal:8080 (the d6e operator can
override it with the D6E_API_URL_FOR_DOCKER env var). Never hardcode
it — always read it from stdin.

  • api_token is a signed, per-execution token scoped to this

workspace + STF. Treat it as a secret; never log it. **SQL endpoint
only** — see [references/external-apis.md](references/external-apis.md).

  • sources maps each workflow input step name directly to its

resolved value — there is no {"output": ...} wrapper. **Previous
STF step outputs are not in sources.** Use workflow input_mappings
with $steps[n] (Effect / JS STF layer); mapped fields arrive in input.
See [references/stdin-sources-vs-steps.md](references/stdin-sources-vs-steps.md).
The value shape depends on the input source type:

  • Library → { "code": "...", "types": "...", "version": "..." }
  • File (JSON content type) → the parsed JSON value
  • File (text content type) → the file body as a string
  • File (binary) → { "filename", "content_type", "size", "data": "<base64>" }

(delivered in sources — not via files API from the container; see
[references/storage-and-files.md](references/storage-and-files.md))

  • Fetch → the parsed JSON response body

Output Format

Success: print exactly one JSON document to stdout and exit 0:

{
  "output": {
    "status": "success",
    ...custom result data
  }
}

The engine parses the entire stdout as a single JSON document with
a top-level output key. Anything else on stdout (log lines, progress
messages, a second JSON document) causes an
Invalid Docker output format error. All logging must go to stderr.

Error: write a detailed message to stderr and exit non-zero:

print(f"ValidationError: missing required field 'operation'", file=sys.stderr)
sys.exit(1)

On a non-zero exit code, d6e reports the workflow step as failed with
the container's stderr as the error message. A JSON body like
{"error": ...} printed to stdout is NOT parsed — put the
human-readable failure reason on stderr, because that is what the user
(and the calling AI agent) will see.

SQL API Access

The api_token authenticates as AuthContext::InternalStf and may call
only the workspace SQL endpoint. Do not use it for saas-proxy, files, or
other d6e APIs — see [references/external-apis.md](references/external-apis.md).

Endpoint: POST {api_url}/api/v1/workspaces/{workspace_id}/sql

Headers: Authorization: Bearer {api_token}, X-Internal-Bypass: true,
X-Workspace-ID: {workspace_id}, X-STF-ID: {stf_id} (all from stdin).

Request: { "sql": "SELECT * FROM my_table LIMIT 10" }

Response: SELECT → { "rows": [...] }; DML → { "affected_rows": N }.

Restrictions: no DDL (DDL_FORBIDDEN); policy allow required
(POLICY_DENIED); plain table names ≤ 23 chars (workspace-scoped rewrite).

Quick Start

Before wiring workflows: stdin sources contains input step results
only (File, Fetch, Library, …). Data from an earlier STF step is mapped via
$steps[n] into input, not into sources. Misreading this is the most
common integration bug — see
[references/stdin-sources-vs-steps.md](references/stdin-sources-vs-steps.md).

Python Implementation

main.py:

#!/usr/bin/env python3
import sys
import json
import requests
import logging

logging.basicConfig(stream=sys.stderr, level=logging.INFO)

def execute_sql(api_url, api_token, workspace_id, stf_id, sql):
    """Execute SQL via D6E internal API"""
    url = f"{api_url}/api/v1/workspaces/{workspace_id}/sql"
    headers = {
        "Authorization": f"Bearer {api_token}",
        "X-Internal-Bypass": "true",
        "X-Workspace-ID": workspace_id,
        "X-STF-ID": stf_id,
        "Content-Type": "application/json"
    }
    response = requests.post(url, json={"sql": sql}, headers=headers)
    response.raise_for_status()
    return response.json()

def process_describe():
    """Return the input schema and available operations."""
    return {
        "status": "success",
        "operation": "describe",
        "data": {
            "input_schema": {
                "type": "object",
                "properties": {
                    "operation": {
                        "type": "string",
                        "enum": ["your_operation", "describe"],
                        "description": "The operation to perform"
                    }
                },
                "required": ["operation"]
            },
            "operations": {
                "your_operation": {
                    "description": "Your operation description",
                    "required": [],
                    "optional": []
                },
                "describe": {
                    "description": "Returns the input schema and available operations",
                    "required": [],
                    "optional": []
                }
            }
        }
    }

def main():
    try:
        input_data = json.load(sys.stdin)
        user_input = input_data["input"]
        operation = user_input.get("operation")

        # Handle describe before any other validation
        if operation == "describe":
            result = process_describe()
        else:
            # Your business logic here
            result = {"status": "success", "message": "Processed"}

        print(json.dumps({"output": result}))
    except Exception as e:
        # The error message MUST go to stderr — d6e reports stderr as
        # the step's failure reason when the exit code is non-zero.
        logging.error(f"{type(e).__name__}: {str(e)}", exc_info=True)
        sys.exit(1)

if __name__ == "__main__":
    main()

Dockerfile:

FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY main.py .
RUN chmod +x main.py
ENTRYPOINT ["python3", "main.py"]

requirements.txt:

requests>=2.31.0

Node.js Implementation

index.js:

const axios = require("axios");

async function executeSql(apiUrl, apiToken, workspaceId, stfId, sql) {
  const response = await axios.post(
    `${apiUrl}/api/v1/workspaces/${workspaceId}/sql`,
    { sql },
    {
      headers: {
        Authorization: `Bearer ${apiToken}`,
        "X-Internal-Bypass": "true",
        "X-Workspace-ID": workspaceId,
        "X-STF-ID": stfId,
        "Content-Type": "application/json",
      },
    }
  );
  return response.data;
}

function processDescribe() {
  return {
    status: "success",
    operation: "describe",
    data: {
      input_schema: {
        type: "object",
        properties: {
          operation: {
            type: "string",
            enum: ["your_operation", "describe"],
            description: "The operation to perform",
          },
        },
        required: ["operation"],
      },
      operations: {
        your_operation: {
          description: "Your operation description",
          required: [],
          optional: [],
        },
        describe: {
          description: "Returns the input schema and available operations",
          required: [],
          optional: [],
        },
      },
    },
  };
}

async function main() {
  try {
    const input = await readStdin();
    const data = JSON.parse(input);
    const { operation } = data.input;

    // Handle describe before any other validation
    let result;
    if (operation === "describe") {
      result = processDescribe();
    } else {
      // Your business logic here
      result = { status: "success", message: "Processed" };
    }

    console.log(JSON.stringify({ output: result }));
  } catch (error) {
    // The error message MUST go to stderr — d6e reports stderr as
    // the step's failure reason when the exit code is non-zero.
    console.error(`${error.name}: ${error.message}`);
    process.exit(1);
  }
}

function readStdin() {
  return new Promise((resolve) => {
    let data = "";
    process.stdin.on("data", (chunk) => (data += chunk));
    process.stdin.on("end", () => resolve(data));
  });
}

main();

Dockerfile:

FROM node:18-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY index.js .
ENTRYPOINT ["node", "index.js"]

Implementation Checklist

When creating a Docker STF, ensure:

  • [ ] Reads JSON from stdin
  • [ ] Outputs exactly ONE JSON document to stdout ({"output": {...}}) — nothing else
  • [ ] Logs to stderr (stdout is for the result only)
  • [ ] On failure: writes the reason to stderr and exits non-zero (d6e surfaces stderr as the error)
  • [ ] Uses small base images (e.g., python:3.11-slim)
  • [ ] Validates input parameters
  • [ ] Reads api_url / api_token / workspace_id / stf_id from stdin (never hardcoded)
  • [ ] Uses environment variables for configuration; secrets are declared via secret_keys (see "Registering the STF in d6e")
  • [ ] Implements the describe operation (returns input schema and available operations)
  • [ ] Finishes within the execution timeout (default 5 minutes)

Best Practices

Security

  • Never log sensitive data (tokens, passwords) — in particular, never

log api_token or the full stdin JSON, which contains it

  • Validate all user inputs
  • The SQL API accepts a raw SQL string only — there is no parameter

binding. Escape string literals by doubling single quotes and
validate identifiers (table/column names) against strict patterns or
allow-lists; never interpolate unescaped user input into SQL

  • Keep dependencies up-to-date

Performance

  • Use multi-stage builds to reduce image size
  • Minimize dependencies
  • Add .dockerignore to exclude unnecessary files
  • Cache pip/npm installations

Error Handling

d6e decides success/failure from the exit code and reports the
container's stderr as the failure reason. So: successful runs print
the {"output": ...} JSON to stdout and exit 0; failed runs write a
descriptive message to stderr and exit non-zero. Include the error
type and a precise reason in stderr, but never full payloads, which may
contain personal data or secrets.

try:
    # Your logic
    result = process_data(input_data)
    print(json.dumps({"output": result}))
except ValueError as e:
    # Validation errors — the stderr text is what users will see.
    # Log only selected safe fields, never the whole user_input.
    logging.error(f"ValidationError: {str(e)} (operation={user_input.get('operation')})")
    print(json.dumps({"error": str(e), "type": "ValidationError"}))
    sys.exit(1)
except Exception as e:
    # Unexpected errors
    logging.error(f"{type(e).__name__}: {str(e)}", exc_info=True)
    sys.exit(1)

Recoverable, domain-level "failures" that the workflow should continue
from (e.g. "no matching rows") are not errors — return them inside
output with a status field and exit 0.

Logging

The stdin document contains api_token. Never log the full stdin JSON
(input_data) or the raw input payload — stderr from failed runs is
surfaced in API error responses and written to the server logs, so
anything you log can leak to users and log storage. Log only selected,
non-secret metadata:

import logging

# Log to stderr
logging.basicConfig(
    stream=sys.stderr,
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)

logging.info("Processing started")
# Log only non-secret metadata — never the full stdin JSON (it contains api_token)
logging.info(f"Processing operation={user_input.get('operation')}")
logging.warning("Deprecated operation used")
logging.error("Failed to process", exc_info=True)

The describe Operation

Every Docker STF must implement a describe operation. This operation returns the input schema and available operations, enabling workflow builders and AI agents to discover what parameters are needed before creating workflows.

Why describe is Required

  • Discoverability: Workflow builders can query the STF to understand its capabilities without reading source code
  • Automation: AI agents can automatically generate correct input_mappings for workflows
  • Validation: The schema enables pre-execution validation of workflow inputs
  • Documentation: Acts as machine-readable, always up-to-date documentation

describe Request

{
  "input": {
    "operation": "describe"
  }
}

describe Response Format

{
  "output": {
    "status": "success",
    "operation": "describe",
    "data": {
      "input_schema": {
        "type": "object",
        "properties": {
          "operation": {
            "type": "string",
            "enum": ["op1", "op2", "describe"],
            "description": "The operation to perform"
          }
        },
        "required": ["operation"]
      },
      "operations": {
        "op1": {
          "description": "Description of operation 1",
          "required": ["param1", "param2"],
          "optional": ["param3"]
        },
        "op2": {
          "description": "Description of operation 2",
          "required": ["param1"],
          "optional": []
        },
        "describe": {
          "description": "Returns the input schema and available operations",
          "required": [],
          "optional": []
        }
      }
    }
  }
}

Implementation Pattern (Python)

def process_describe():
    """Return the input schema and available operations."""
    return {
        "status": "success",
        "operation": "describe",
        "data": {
            "input_schema": {
                "type": "object",
                "properties": {
                    "operation": {
                        "type": "string",
                        "enum": ["my_operation", "describe"],
                        "description": "The operation to perform"
                    },
                    "param1": {
                        "type": "string",
                        "description": "Description of param1"
                    }
                },
                "required": ["operation"]
            },
            "operations": {
                "my_operation": {
                    "description": "What this operation does",
                    "required": ["param1"],
                    "optional": []
                },
                "describe": {
                    "description": "Returns the input schema and available operations",
                    "required": [],
                    "optional": []
                }
            }
        }
    }

def main():
    input_data = json.load(sys.stdin)
    user_input = input_data["input"]
    operation = user_input.get("operation")

    # Handle describe before any other validation
    if operation == "describe":
        result = process_describe()
    else:
        # Validate and process other operations
        ...

    print(json.dumps({"output": result}))

Best Practice: Workflow Creation with describe

When creating workflows that use Docker STFs, always follow this process:

  1. Run describe first to get the input schema
  2. Map all required parameters in input_mappings based on the schema
  3. Include optional parameters where appropriate
# Step 1: Discover the STF's capabilities
echo '{"workspace_id":"...","stf_id":"...","caller":null,"api_url":"...","api_token":"...","input":{"operation":"describe"},"sources":{}}' \
  | docker run --rm -i my-stf:latest

# Step 2: Use the returned schema to build the workflow input_mappings

Common Patterns

Data Validation Pattern

def validate_input(user_input):
    required_fields = ["operation", "table_name"]
    for field in required_fields:
        if field not in user_input:
            raise ValueError(f"Missing required field: {field}")

    if user_input["operation"] not in ["query", "insert", "update"]:
        raise ValueError(f"Invalid operation: {user_input['operation']}")

    return True

# Usage
try:
    validate_input(input_data["input"])
except ValueError as e:
    print(f"ValidationError: {e}", file=sys.stderr)
    sys.exit(1)

Database Query Pattern

def sql_quote(value):
    """Quote a value as a SQL string literal (doubles single quotes).

    The d6e SQL API has no bind parameters, so escaping is the only
    defense against injection.
    """
    escaped = str(value).replace("'", "''")
    return f"'{escaped}'"

def safe_query(api_context, table_name, filters):
    """Query a table with identifier validation and escaped literals."""
    # Validate the table name (d6e table names are <= 23 chars)
    if not table_name.isidentifier() or len(table_name) > 23:
        raise ValueError(f"Invalid table name: {table_name}")

    # Build WHERE clause safely
    where_conditions = []
    for key, value in filters.items():
        # Column names must be identifiers — reject anything else
        if not key.isidentifier():
            raise ValueError(f"Invalid column name: {key}")
        where_conditions.append(f"{key} = {sql_quote(value)}")

    where_clause = " AND ".join(where_conditions) if where_conditions else "1=1"
    sql = f"SELECT * FROM {table_name} WHERE {where_clause} LIMIT 100"

    return execute_sql(
        api_context["api_url"],
        api_context["api_token"],
        api_context["workspace_id"],
        api_context["stf_id"],
        sql
    )

External API Pattern

import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

def create_session():
    """Create session with retry logic"""
    session = requests.Session()
    retry = Retry(
        total=3,
        backoff_factor=0.3,
        status_forcelist=[500, 502, 503, 504]
    )
    adapter = HTTPAdapter(

Related Skills

Get the best new skills
in your inbox

Weekly roundup of top Claude Code skills, MCP servers, and AI coding tips.