# Running Python with Flights
> Build scheduled Python workflows in MotherDuck for ingest, transformation, sharing, and operational tasks.
A **Flight** is a Python program that runs on MotherDuck, on demand or on a recurring schedule. Use Flights to pull data in from external sources, refresh aggregates, run dbt, scrape a page, or post a scheduled summary to Slack.

Flights complement SQL: where SQL handles transformation against your tables, Flights add everything Python can do (HTTP calls, the full PyPI ecosystem, file processing, custom logic) right next to your data.

:::info
For scheduled or production-like Flights, test with an on-demand run first, [create the Flight as a service account](/key-tasks/flights/flights-authentication-config-and-secrets/#service-accounts-for-production-flights), and keep its database permissions as narrow as the workload allows. For Git-based deployment, see [managing Flights as code](/key-tasks/flights/managing-flights-as-code/).
:::

The **Flights** page in the MotherDuck UI lists every Flight in your organization with its schedule and last run status.

![Flights list page](img/flights.png)

## Anatomy of a Flight

| Field | What it is |
|---|---|
| **Name** | Human-readable identifier shown in the UI and logs. |
| **Source code** | A single-file Python program. The runtime executes it as a plain script, so end it with `if __name__ == "__main__": main()` to invoke your entrypoint. |
| **Requirements** | A `requirements.txt`-style list of pip packages, one per line. |
| **MotherDuck token** | The name of an [access token](/key-tasks/authenticating-and-connecting-to-motherduck/authenticating-to-motherduck/). MotherDuck injects the token value into the Flight as the `MOTHERDUCK_TOKEN` environment variable. |
| **Config** | A map of non-sensitive key/value pairs surfaced to the Flight as environment variables (for example, a region or a batch size). |
| **Schedule** | A standard 5-field cron expression in UTC. Omit to make the Flight on-demand only. |

Each edit to source code, requirements, config, or the token produces a fresh version. Renaming a Flight or changing its schedule is a metadata-only update and does not produce one.

## Create your first Flight

### MCP / AI agent

Connect the [MotherDuck MCP Server](/sql-reference/mcp/) to your AI agent, then ask it to create a Flight:

> "Create a Flight named `heartbeat` that connects to MotherDuck, creates `docs_playground.heartbeat` if it doesn't exist, inserts one row, and prints how many rows it wrote. Use the latest MotherDuck-supported DuckDB version in the requirements."

The agent will call `create_flight` with the right `source_code` and `requirements_txt`. It can then call `run_flight` to trigger an immediate run and `get_flight_logs` to read the output back into the conversation.

You can iterate with the agent the same way you would on a script: "add a config value for the table name and use it instead of hard-coding `heartbeat`."

:::tip
If the agent has a terminal, the [MotherDuck CLI](/getting-started/interfaces/motherduck-cli/agents/) is the more efficient path for authoring: `motherduck flight pull` and `motherduck flight push` keep the Python source in a local file rather than in the conversation, and `motherduck flight list --output json` returns a listing the agent can filter with `jq`. See [choosing between the CLI and MCP](/getting-started/interfaces/motherduck-cli/agents/#choosing-between-the-cli-and-mcp).
:::

### SQL

Create a Flight directly with SQL:

#### Create the heartbeat Flight

Database: `docs_playground`

```sql
SELECT flight_id, flight_name, current_version
FROM MD_CREATE_FLIGHT(
    name := 'heartbeat_docs_demo',
    requirements_txt := array_to_string([
        'duckdb==1.5.2'
    ], chr(10)),
    source_code := $flight$
import duckdb

def main():
    con = duckdb.connect("md:")
    con.execute("""
        CREATE TABLE IF NOT EXISTS docs_playground.heartbeat (
            ts TIMESTAMP DEFAULT current_timestamp,
            message VARCHAR
        )
    """)
    con.execute("INSERT INTO docs_playground.heartbeat (message) VALUES ('hello from a flight')")
    print("wrote 1 row to docs_playground.heartbeat")

if __name__ == "__main__":
    main()
$flight$
);
```

Trigger an on-demand run. The `MD_*` Flight table functions only accept literal parameters, not subqueries, so store the Flight ID in a SQL variable first:

#### Set the heartbeat Flight ID

Database: `docs_playground`

```sql
SET VARIABLE heartbeat_flight_id = (
    SELECT flight_id
    FROM MD_LIST_FLIGHTS()
    WHERE flight_name = 'heartbeat_docs_demo'
    ORDER BY created_at DESC
    LIMIT 1
);
```

#### Run the heartbeat Flight

Database: `docs_playground`

```sql
SELECT *
FROM MD_RUN_FLIGHT(
    flight_id := getvariable('heartbeat_flight_id')
);
```

Inspect the row the Flight wrote:

#### Read the heartbeat table

Database: `docs_playground`

```sql
SELECT *
FROM docs_playground.heartbeat
ORDER BY ts DESC
LIMIT 5;
```

The SQL above is the same control surface shown in the reference:

```sql
SELECT flight_id, flight_name, current_version
FROM MD_CREATE_FLIGHT(
    name := 'heartbeat',
    source_code := $$
import duckdb

def main():
    con = duckdb.connect("md:")
    con.execute("""
        CREATE TABLE IF NOT EXISTS docs_playground.heartbeat (
            ts TIMESTAMP DEFAULT current_timestamp,
            message VARCHAR
        )
    """)
    con.execute("INSERT INTO docs_playground.heartbeat (message) VALUES ('hello from a flight')")
    print("wrote 1 row to docs_playground.heartbeat")

if __name__ == "__main__":
    main()
$$,
    requirements_txt := array_to_string([
        'duckdb==1.5.2'
    ], chr(10))
);
```

## What happens when a Flight runs

When you trigger a run (manually or on schedule), MotherDuck:

1. Allocates a Python runtime for the Flight.
2. Injects `MOTHERDUCK_TOKEN` and your `config` keys into the environment.
3. Installs the packages in `requirements.txt`.
4. Executes `main()`, capturing stdout and stderr.
5. Records the run's status and logs.

Runs are asynchronous. A new run starts in `RUN_STATUS_PENDING`, moves to `RUN_STATUS_RUNNING`, and ends in one of `RUN_STATUS_SUCCEEDED`, `RUN_STATUS_FAILED`, or `RUN_STATUS_CANCELLED`. Poll for completion with `list_flight_runs` (MCP) or `MD_LIST_FLIGHT_RUNS` (SQL).

## Versioning

Every edit to a Flight's content fields (`source_code`, `requirements_txt`, `config`, or the access token) produces a fresh version. Renames and schedule changes do not.

When a run starts, it locks to the version that was current at that moment. If you update the Flight while a run is in progress, that run finishes against the version it started with; only the next run picks up the updated source.

You can browse versions in the MotherDuck UI or read them programmatically with `list_flight_versions` and `get_flight` (passing a specific version number).

## Choose who can run a Flight

A new Flight can only be run by its owner. To let teammates run a Flight you own, for example from a button in a [Dive app](/key-tasks/dives/run-flights-from-dives/), give them `run` access. A run always uses the owner's token and secrets, whoever starts it. `run` access doesn't share the Flight's source code, logs, or credentials.

To manage who can run a Flight in the MotherDuck UI:

1. Open the access dialog in one of these ways:
   - On the Flight's page, click **Access**.
   - On the **Flights** page, click **Manage access** in the Flight's row menu, or click its **Can run** cell.
2. To add a role or user, search for them in **Find roles or users**. To let everyone in your organization run the Flight, including service accounts and people who join later, select **Run** for **Anyone in the organization**.
3. Select or clear **Run** for each row, then click **Save**.

![Manage access dialog for a Flight, with the owner, the organization, the order_approvers role, and a user](./img/flight-access.png)

**Save** applies all of your changes together. If one change fails, none of them are applied, and the dialog keeps your edits so you can fix them and try again.

The **Can run** column on the **Flights** page shows who can run each Flight: **Only the owner**, **Anyone in the organization**, or the roles and users with access. When there's more than one role or user, it shows how many, such as **2 roles**. Hover over the count to see their names.

Only a Flight's owner can give `run` access. Organization Admins can open the access dialog for any Flight to remove access, but can't add it. People with `run` access can start the Flight and check the runs they started, including those runs' config values, which include the Flight's stored config. They can't read its source code or logs, or edit, cancel, or delete it. Put values that must stay hidden in [secrets](/key-tasks/flights/flights-authentication-config-and-secrets/). They also don't see the Flight in the MotherDuck UI, because the **Flights** page lists a Flight only for its owner and organization Admins. They run it from a [Dive app](/key-tasks/dives/run-flights-from-dives/) or with SQL, using [`MD_RUN_FLIGHT`](/sql-reference/motherduck-sql-reference/flights/md-run-flight/).

The dialog manages the same grants as SQL. To make the same change from SQL, use [`GRANT RUN ON FLIGHT`](/sql-reference/motherduck-sql-reference/flights/grant-run-on-flight/):

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

## Related resources

- [Flights concept](/concepts/compute/flights) — the mental model and where Flights fit alongside SQL, Dives, and external orchestrators.
- [MotherDuck MCP Server](/sql-reference/mcp/) — `create_flight`, `run_flight`, and the rest of the Flight tool surface for AI agents.
- [`motherduck flight`](/sql-reference/motherduck-cli/flight/) — build, push, run, and monitor Flights from the terminal, and the cheaper path for coding agents.
- [Managing Flights as code](/key-tasks/flights/managing-flights-as-code/) — version source in Git and deploy with a service account using Blueprints or the CLI.
- [Flight Explainer](/key-tasks/flights/observability/explain-flight-runs/) — see every run as a live, step-by-step view of what ran, what failed, and how long each step took.


---

## Docs feedback

MotherDuck accepts optional user-submitted feedback about this page at `GET https://motherduck.com/docs/api/feedback/agent`.
For agents and automated tools, feedback submission should be user-confirmed before sending.

URL-encode query parameter values and send a GET request:

```text
GET https://motherduck.com/docs/api/feedback/agent?page_path=%2Fkey-tasks%2Fflights%2F&page_title=Running%20Python%20with%20Flights&text=<url-encoded user feedback, max 2000 characters>
```

Optionally append `&source=<url-encoded interface identifier>` such as `claude.ai` or `chatgpt`.

`page_path` and `text` are required; `page_title` and `source` are optional. Responses: `200 {"feedback_id": "<uuid>"}`, `400` for malformed query parameters, and `429` when rate-limited.
