MDK Logo

Write actions

How to add an approval flow to your MDK app

TL;DR

Run from your project folder (holding mdk.yaml). Runtime: mdk run. The Kernel key is written to .mdk/kernel.key.

  • A write runs only when both the app's grant and the operator's own spec.rbac rules allow it

Overview

This guide shows how to expose approval-gated write actions as Gateway routes, then submit, review, approve, reject, or cancel them from a React app. MDK ships no React hooks for actions: the app calls its own routes with useQuery / useMutation.

Prerequisites

  • A stack that runs with mdk run, with an actions app mounted
  • Operator rules in spec.rbac for who may stage and approve writes. The Gateway checks each route's verb on ops-actions/* (get to read the queue, create to submit, update to vote, delete to cancel), and the Kernel then checks the operator's own actions: read, actions: write, and actions: vote rules, and devices: write on the devices a push targets. What a route's auth still does is in the Gateway's security model
  • A Worker that accepts the action: only a Worker with the actions service, and the action on its allowlist, answers the Kernel's write.calls.request with calls. The Workers mdk run starts from packages run on WorkerRuntimeV2 with no services, so a push to them stages nothing and ends in ERR_KERNEL_ACTION_CALLS_EMPTY. Host a Worker on WorkerRuntime with an ActionsService for the action to stage. A Worker without that service shows in the push's errors; one whose allowlist or devices don't match the push is left out without an error
  • If present, your React app is wrapped in <MdkProvider apiBaseUrl={...}>

Create the actions app first, then call its routes from the UI.

Create an actions app

To enable approval-gated writes, create an app that exposes HTTP routes for the write-action workflow. Each route calls the corresponding method on req.mdk, the request's Kernel client. For a signed-in user it acts for that user: the Kernel verifies their token, checks both the app's grant and the user's own spec.rbac rules, and records the user as the voter.

The paths shown below (/auth/actions*) are illustrative examples. You may use any path structure that fits your app's routing pattern. Nothing in MDK declares these routes: your app's route table does, and the HTTP reference generated from it lists them.

Required routes

MethodExample PathRoute idsafetyreq.mdk methodPurpose
GET/auth/actionsops-actions.queryread-onlyqueryActions()Query actions by lifecycle state (voting, ready, executing, done)
POST/auth/actions/votingops-actions.pushwritepushAction()Submit a single action for approval
POST/auth/actions/voting/batchops-actions.push-batchwritepushActionsBatch()Submit multiple actions for approval
PUT/auth/actions/voting/:id/voteops-actions.votewritevoteAction()Cast an approval or rejection vote on an action
DELETE/auth/actions/voting/cancelops-actions.cancelwritecancelActionsBatch()Cancel pending actions by IDs

Each route gets its own entry in plugin/mdk-plugin.json, in the shape the manifest example shows for ops-actions.push, and its own controller.

App structure

Start from mdk create app ops-actions. Don't name the app actions: that is a Kernel resource name, so the CLI won't grant it anything. Replace the scaffold's summary route, its controller and test/summary.js, with one controller per route:

apps/ops-actions/
├── mdk-app.yaml
└── plugin/
    ├── mdk-plugin.json
    └── controllers/
        ├── query.js
        ├── push.js
        ├── push-batch.js
        ├── vote.js
        └── cancel.js

Grant the app

The app's own service account needs Kernel access for actions, or every route answers 403 ERR_KERNEL_ACTION_FORBIDDEN. Request it in mdk-app.yaml:

permissions:
  - resources: [actions]
    verbs: [read, write, vote]
  - resources: [devices]
    verbs: [read, write]

Then replace the app's role in spec.rbac with the new request, and apply it if the Kernel is running:

mdk add app ops-actions --no-install --accept-permissions
mdk rbac apply

Example controller (push.js)

'use strict'

module.exports = async function pushAction (req) {
  // req.mdk acts for the user the Gateway verified: Kernel checks their rules and the app's
  const reply = await req.mdk.pushAction({
    query: req.body.query,       // Device query/selector
    action: req.body.action,     // Action name from worker contract
    params: req.body.params,     // Action parameters
    voter: req._info.sub         // Required by the payload; Kernel records the verified user
  })

  // The Kernel refused the request itself, such as an empty action or an invalid query
  if (reply.error) throw new Error(reply.error)

  // Nothing staged: throw the Kernel's ERR_* code first, then each Worker's refusal
  if (reply.id === null) {
    const code = reply.errors.find((e) => e.startsWith('ERR_'))
    throw new Error([code, ...reply.errors.filter((e) => e !== code)].join('; '))
  }

  // Staged: errors names any Worker that failed to answer, not one the push didn't match
  return { id: reply.id, errors: reply.errors }
}

pushAction resolves rather than throws when the push is refused. A request the Kernel refuses outright comes back as { error }. Otherwise id is null when nothing was staged, and errors holds the Kernel's code (why a push is refused) and a <workerId>: <error> entry for each Worker that failed to answer. A Worker whose allowlist or devices don't match the push is left out of both, so an empty errors doesn't mean every Worker took part. Returned as is, a refused push reaches the caller as 200. Thrown with the code first, it gets the status the controller rule gives that code.

Manifest example (mdk-plugin.json)

{
  "routeTableVersion": "1",
  "name": "ops-actions",
  "version": "1.0.0",
  "description": "Approval-gated write action APIs",
  "routes": [
    {
      "id": "ops-actions.push",
      "handler": "./controllers/push.js",
      "auth": true,
      "http": {
        "method": "POST",
        "path": "/auth/actions/voting",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": ["query", "action", "params"],
                "properties": {
                  "query": { "type": "object" },
                  "action": { "type": "string" },
                  "params": { "type": "array" }
                }
              }
            }
          }
        }
      },
      "description": "Submit a write action for approval",
      "safety": "write"
    }
  ]
}

These routes stage fleet-changing writes, so grant them narrowly in spec.rbac. A write is staged, not executed, until it is approved; "safety": "write" keeps the route out of mdk run mcp unless it runs with --allow-write (safety). Auth and permissions covers the patterns.

Mount the app

Declare it in mdk.yaml and start the stack with mdk run. Your React code calls /auth/actions* at the Gateway root, so mount the app at / rather than the default /apps/<name>:

spec:
  apps:
    - name: ops-actions
      package: ops-actions
      mount: /

Running it from your own code instead goes through startGateway({ apps }) and createAppRuntime(), as starting apps from code shows.

Calls through config.mdkClient act as the app alone: the Kernel checks only the app's grant and records the app as the voter. Use req.mdk for anything a user asked for, so their own devices: write and actions rules gate the write.

Call the routes from a React app

Read the queue with useQuery and send writes with useMutation, both re-exported by @tetherto/mdk-react-adapter. Read the configured transport with getFetcher(queryClient) and use it for queries and mutations. With <MdkProvider auth={auth} fetcher={auth.fetcher}>, where auth is a passwordAuth() provider, this transport sends the access token, refreshes it on 401, retries the request, and parses the JSON body. Invalidate the queue after each write so the list refreshes:

import { useMdkContext, useMutation, useQuery, useQueryClient } from "@tetherto/mdk-react-adapter";
import { getFetcher } from "@tetherto/mdk-ui-foundation";

const QUEUE_KEY = ["actions", "voting"];

type PendingAction = { id: string };

function PendingActions() {
  const { apiBaseUrl } = useMdkContext();
  const queryClient = useQueryClient();
  const fetcher = getFetcher(queryClient);
  if (!fetcher) throw new Error("MDK fetcher is not configured");

  const { data: pending = [] } = useQuery({
    queryKey: QUEUE_KEY,
    // Your GET route decides how it maps the request onto `queryActions()` and what it returns;
    // this example assumes it returns the voting actions as an array. `fetcher` parses the body
    // and returns it as the type you give it, so name that type or `pending` arrives as `unknown`.
    queryFn: () => fetcher<PendingAction[]>(`${apiBaseUrl}/auth/actions`),
    refetchInterval: 10_000,
  });

  const vote = useMutation({
    mutationFn: ({ id, approve }: { id: string; approve: boolean }) =>
      fetcher(`${apiBaseUrl}/auth/actions/voting/${id}/vote`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ approve }),
      }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: QUEUE_KEY }),
  });

  return pending.map((action) => (
    <button key={action.id} type="button" onClick={() => vote.mutate({ id: action.id, approve: true })}>
      Approve {action.id}
    </button>
  ));
}

Submit (POST /auth/actions/voting) and cancel (DELETE /auth/actions/voting/cancel) follow the same useMutation shape. Approved actions become command requests once the vote thresholds are met; the item then leaves the voting queue.

For complete mdk-client method signatures and protocol details, see the mdk-client README and actions integration tests.

Next steps

On this page