Skip to main content

Build Dive apps

A Dive app is a Dive people act in, not only read. Add a button or a form that runs a Flight, and viewers can approve an order, refresh a pipeline, or submit a correction without leaving the Dive. The Flight can also call other services, such as posting to Slack or opening a ticket. When the run finishes, the Dive shows the new data.

The Dive itself stays read-only. The Flight does the writing, as its owner, with the owner's token and secrets. The Dive starts the run, follows its status, and reruns its queries when the run succeeds:

Here, a viewer approves order #1042 in an Order approvals Dive, which runs the decide_order Flight built in this guide:

A viewer clicks Approve on order 1042 in an Order approvals Dive. A banner shows the run queued and updating, then Run #4 succeeded. Orders updated, and the order's status changes from pending to approved

What happens in the recording:

  1. The viewer clicks Approve on #1042. The Dive calls run({ ORDER_ID: "1042", DECISION: "approved" }) from useRunFlight, which calls MD_RUN_FLIGHT with those values as this run's config. The banner reads Starting…, and every button is disabled so the viewer can't start a second run.
  2. The run is queued. useRunFlight returns the new run's number, and useFlightRun starts checking its status. While the status is PENDING, the banner reads Run #4: Queued….
  3. The Flight runs. The status moves to RUNNING, and the banner reads Updating order…. The Flight runs as its owner, reads ORDER_ID and DECISION from its environment, and updates the row in ops.main.orders.
  4. The run succeeds. useFlightRun reports SUCCEEDED, and its onFinished callback runs the orders query again. The banner reads Run #4 succeeded. Orders updated., and #1042 moves out of the pending list as approved.

The Dive only reads data. The write happens in the Flight, and the Dive learns about it by following the run and querying again.

What you can build​

PatternWhat the viewer doesWhat the Flight does
FormFills in fields and clicks Submit.Inserts or updates rows with the submitted values, for example a forecast override or a data correction.
Row actionClicks Approve on a row.Acts on that record, for example approves an order, closes a ticket, or reprocesses one file.
Refresh buttonClicks Refresh data.Reruns the pipeline that feeds the Dive, for example pulling the latest CRM records.
Background taskClicks Send report.Does work outside MotherDuck, for example calls an API, sends an email, or posts to Slack.

Prerequisites​

Step 1: Write a Flight that takes input​

A Dive passes input to a Flight as config values, which the Flight reads as environment variables. Define every key the Dive will send when you create the Flight, because a run can only override keys the Flight already has.

This Flight approves or rejects one order:

SELECT flight_id
FROM MD_CREATE_FLIGHT(
name := 'decide_order',
config := MAP {'ORDER_ID': '', 'DECISION': ''},
requirements_txt := 'duckdb==1.5.3',
source_code := $$
import os
import duckdb

def main():
order_id = os.environ["ORDER_ID"]
decision = os.environ["DECISION"]
if decision not in ("approved", "rejected"):
raise SystemExit(f"unknown decision: {decision!r}")

con = duckdb.connect("md:")
con.execute(
"UPDATE ops.main.orders SET status = ?, decided_at = now() WHERE order_id = ?",
[decision, order_id]
)
print(f"order {order_id}: {decision}")

if __name__ == "__main__":
main()
$$
);
warning

Treat config values as input from whoever clicks the button. Validate them, and pass them to SQL as parameters, as above, rather than formatting them into the query text.

Note the flight_id the call returns. The Dive needs it in Step 3. To look it up later, run SELECT flight_id, flight_name FROM MD_LIST_FLIGHTS();.

Step 2: Test the Flight from SQL​

Before you wire up a button, run the Flight the way the Dive will: with config values for one run. These are the same calls useRunFlight and useFlightRun make. Store the Flight's ID in a variable, because the MD_* Flight functions only accept literals and variables:

SET VARIABLE decide_order_id = (
SELECT flight_id FROM MD_LIST_FLIGHTS() WHERE flight_name = 'decide_order'
);

Start a run with config values for this run only. The Flight's stored config doesn't change:

SET VARIABLE run_number = (
SELECT run_number
FROM MD_RUN_FLIGHT(
flight_id := getvariable('decide_order_id'),
config := MAP {'ORDER_ID': '1042', 'DECISION': 'approved'}
)
);

Check the run until its status is SUCCEEDED, FAILED, or CANCELLED. Older clients report these with a RUN_STATUS_ prefix, such as RUN_STATUS_SUCCEEDED:

SELECT status, exit_code, started_at, ended_at, config
FROM MD_GET_FLIGHT_RUN(
flight_id := getvariable('decide_order_id'),
run_number := getvariable('run_number')
);

If it failed, read the output. As the Flight's owner, you can read every run's logs:

SELECT line
FROM MD_GET_FLIGHT_LOGS(
flight_id := getvariable('decide_order_id'),
run_number := getvariable('run_number')
)
ORDER BY line_number;

Then confirm the write landed:

SELECT order_id, status, decided_at
FROM ops.main.orders
WHERE order_id = '1042';

Once the Dive is live, every click is a run. To see what viewers did, list the recent runs with who started each one and the values it used:

SELECT run_number, status, started_by_name, config['ORDER_ID'] AS order_id, config['DECISION'] AS decision, created_at
FROM MD_LIST_FLIGHT_RUNS(flight_id := getvariable('decide_order_id'))
ORDER BY run_number DESC
LIMIT 20;

started_by_name is NULL for scheduled runs and for runs started before this column existed. Only the Flight's owner and the organization's Admins can list its runs.

Step 3: Add the button to the Dive​

Ask your AI agent to add the action to the Dive:

"Add an Approve and a Reject button to each pending order in my orders Dive. They should run the decide_order Flight with ORDER_ID and DECISION, show the run's status, and refresh the table when it succeeds."

The agent looks up the Flight's ID, adds the useRunFlight and useFlightRun hooks, and saves a new version of the Dive.

A few rules keep Dive apps predictable:

  • Run only on a click. Every call to run starts a new run. Don't call it while rendering, in useEffect, or on a timer.
  • Pass strings. Config values must be strings, so convert numbers, dates, and booleans first.
  • Write the Flight's ID into the Dive. Don't look it up by name inside the Dive: MD_LIST_FLIGHTS() lists only the viewer's own Flights (Admins see the organization's), so most viewers would find nothing.
  • A started run isn't a finished run. useRunFlight succeeds when the run starts. Follow it with useFlightRun, which checks the run's status until it ends, and refetch in onFinished.
  • Show progress and errors. Disable the button while a run is starting or being checked, and show errors in words the viewer understands.
  • Handle viewers who can't run the Flight. The button appears for everyone who can view the Dive, and MotherDuck checks access only when the run starts. A viewer without access gets an error in useRunFlight's error. If the Dive doesn't show error, clicking the button does nothing visible. Show a message such as "You don't have access to run this. Ask the Dive's owner.", and keep the rest of the Dive working.

Step 4: Show the new data​

Refetch the queries that read the tables the Flight writes when useFlightRun reports SUCCEEDED, as in the example above. A Dive that reads the database directly sees the new rows right away.

Before and after: on the left, order 1042 is pending with Approve and Reject buttons. On the right, after the run, a banner reads Run #4 succeeded. Orders updated, and order 1042 is approved

Before the click, #1042 is pending and has Approve and Reject buttons. After the run succeeds, the Dive queries again and gets the row with its new status, so it shows as approved with no buttons, and the banner confirms which run made the change.

If the Dive reads the Flight's output through a Share, the Share picks up new data automatically within about a minute. When viewers must see it immediately, end the Flight with CREATE SNAPSHOT OF "<database>", then run REFRESH DATABASE "<alias>" in the Dive before refetching. Both steps cost performance: CREATE SNAPSHOT blocks other writes to the database while it runs, and REFRESH DATABASE makes the next queries read cold data. Use them only when the delay matters.

Step 5: Let others run the Flight​

Anyone who can view the Dive can click its buttons, but MotherDuck runs the Flight only for viewers who own it or have run access to it. Grant run to the people the Dive is for:

GRANT RUN ON FLIGHT '<flight_id>' TO ROLE order_approvers;

Grantees are USER <username>, ROLE <role_name>, or ORGANIZATION, separated by commas. Only the Flight's owner can grant run. Admins can list and revoke run grants on any Flight in the organization, but can't add them. The GRANT statement takes the Flight's ID as a quoted string, not its name. See GRANT RUN ON FLIGHT for the full syntax.

Preset roles nest: Admin is a member of Builder, and Builder of Explorer. A grant to ROLE explorer reaches every Builder and Admin too.

Grant to several grantees at once, check who has access, and remove a grantee:

GRANT RUN ON FLIGHT '<flight_id>' TO USER duck, ROLE finance;

SHOW GRANTS ON FLIGHT '<flight_id>';

REVOKE RUN ON FLIGHT '<flight_id>' FROM USER duck;

To audit access across several Flights, use the MD_LIST_FLIGHT_GRANTEES table function, which takes the ID as a UUID:

SELECT grantee_name, grantee_type
FROM MD_LIST_FLIGHT_GRANTEES('<flight_id>'::UUID)
ORDER BY grantee_type, grantee_name;

A grantee can read only the runs they started, one at a time by run number, with MD_GET_FLIGHT_RUN. This is what useFlightRun does. They can't list the Flight's runs with MD_LIST_FLIGHT_RUNS, and they can't read its logs.

You can also ask your AI agent to grant access. It recommends the grants and waits for you to confirm before it applies them.

A run grant lets someone start the Flight, never act as its owner elsewhere. An Admin can see and stop any Flight in the organization, but runs it only with a grant:

OwnerAdminrun grantNo grant
Run the FlightYesWith a run grantYesNo
See runs' status, exit codes, and config valuesAll runsAll runsRuns they startedNo
Read its logs or source codeYesYesNoNo
Cancel a runYesYesNoNo
Edit or delete itYesNoNoNo
Manage run grantsAdd, list, revokeList, revokeNoNo

Keep these in mind when you grant access:

  • The Flight always runs as its owner, with the owner's token, secrets, and database permissions, whoever clicks the button. Grant run only on Flights whose writes you're comfortable with anyone in the grant making.
  • Config values are visible in the run history to the owner and Admins, and to each grantee for the runs they started. Put values that must stay hidden in secrets, not config.
  • A grant to the organization includes its service accounts. To limit a Flight to specific people, grant to a role that has only those people.
  • Users with no roles can't run Flights, even with a grant.

Where Dive apps can run Flights​

Dives can run Flights in the MotherDuck web app, in the MotherDuck MCP Dive viewer, and in the CLI's local preview with motherduck dive watch. A button returns This Dive can't run Flights. in two places:

  • Embedded Dives never run Flights.
  • The MCP Dive viewer, when your AI tool blocks its direct connection to MotherDuck. The viewer then sends the Dive's queries through the MCP server, which runs only read-only SQL, so runs are off.

Troubleshooting​

Message or symptomCauseFix
Nothing happens when a viewer clicks the button.The run was refused, and the Dive doesn't show useRunFlight's error.Render error, so viewers see why.
This Dive can't run Flights.The Dive is shown somewhere runs are switched off: an embed, or the MCP Dive viewer when your AI tool blocks its direct connection.Open the Dive in the MotherDuck web app.
A not-found error, or You can only run or modify Flights that you own. Ask the owner to give you access to run this one.The viewer doesn't own the Flight and has no run grant.Ask the owner to grant run.
Flights are not available for restricted members ...The viewer has no roles, or the Dive connects with a read scaling token.Ask an Admin to assign the viewer a role.
Only a Flight's owner and the admins of its organization can list its runs. ...A grantee called MD_LIST_FLIGHT_RUNS.Read the run you started by number with MD_GET_FLIGHT_RUN.
The run succeeds but the Dive shows old data.The Dive didn't refetch, or reads a Share that hasn't updated yet.Call refetch() in onFinished, and see Step 4 for Shares.
The run fails right away.The Flight raised an error, often on an unexpected config value.The Flight's owner can read the run's logs. See Monitoring and debugging Flights.