ReferenceWriting a Tool library

Language specification

Runtime

Guides

Background

The Flow Book

Writing a Tool library

On this page

Your program needs to call something outside Flow: a payment API, a database, a model. You write that code as a Tool library, a directory with a flow.toml. Its Tools are Python or Rust functions, or the tools of an MCP server. flow build writes the Flow side of the library, its contract, from that code, and a program imports the directory by its path.

Start a library

Each toolkit lays out a library and a first contract with its own new command. The Python toolkit installs with uv tool install flow-lang-toolkit:

flow-toolkit-python new payments
payments/  flow.toml             [process] command = "flow-toolkit-python serve payments"  payments/__init__.py  one Tool to start from  tests/test_payments.py  contract/lib.flow     generated; commit it

A Python library needs no environment set up: the toolkit serves it on the Python it was installed with. If it uses packages:

  1. Declare them in a pyproject.toml.
  2. Run uv lock to write uv.lock beside it.
  3. Commit both files.

The toolkit makes an environment from the lock in its own cache the first time it serves the library, and makes it again only when the lock changes. Nothing is written in the library's directory. For editor completion, add flow-lang-toolkit as a development dependency.

flow-toolkit-rust new ledger does the same with a Cargo.toml, a Cargo.lock and a flow.toml that names flow-toolkit-rust, which a Flow release installs beside flow. The toolkit builds the library when it serves or extracts it, as cargo run would, and keeps the build in its own cache. Dependencies and build settings live in the native project files, and flow.toml repeats none of them (The host boundary). A library in another language is a [process] library (Write a library in another language).

Write Tools in Python

Mark each Tool with @tool and write its parameter and return types. The types are what crosses between Flow and your code: records are dataclasses, a sum is a union of dataclasses marked @variant, a distinct type over another is a NewType, and a type parameter is a TypeVar.

from dataclasses import dataclassfrom datetime import timedeltafrom typing import NewTypefrom flow_toolkit import tool, variant, context, Result, Ok, Err, NetworkErrorimport stripePaymentId = NewType("PaymentId", str)RefundId = NewType("RefundId", str)@dataclassclass Receipt:    id: RefundId@variant@dataclassclass Declined:    code: str@variant@dataclassclass RateLimited:    retry_after: timedeltaPayError = Declined | RateLimited@tooldef refund(order: PaymentId, cents: int) -> Result[Receipt, PayError]:    """Refund part of a captured charge. The key makes a repeat safe."""    try:        r = stripe.Refund.create(payment_intent=order, amount=cents,                                 idempotency_key=str(context().key))    except stripe.error.CardError as e:        return Err(Declined(e.code))    except stripe.error.RateLimitError:        return Err(RateLimited(timedelta(seconds=60)))    except stripe.error.APIConnectionError as e:        raise NetworkError(sent=True, reason=str(e))   # it may have reached Stripe    return Ok(Receipt(RefundId(r.id)))

flow build payments reads that code, without running it, and writes the contract. The docstring becomes a doc comment, and each declaration names the native definition it came from, so an editor can jump to it:

// Generated by flow build from python module payments. Do not edit.use "std@v1/duration"// from payments/__init__.py: PaymentIdpub type PaymentId(pub Text)// from payments/__init__.py: RefundIdpub type RefundId(pub Text)// from payments/__init__.py: Receiptpub type Receipt {    pub id: RefundId,}// from payments/__init__.py: PayErrorpub type PayError {    Declined { code: Text },    RateLimited { retry_after: duration.Duration },}/// Refund part of a captured charge. The key makes a repeat safe.// from payments/__init__.py: refundpub flow refund(order: PaymentId, cents: Int) -> Result<Receipt, PayError>
Open snippet in Playground (new tab) ↗

A program then writes use "./payments" and calls payments.refund(order, cents), which has the type Result<Result<payments.Receipt, payments.PayError>, ToolProblem>.

When a Tool calls an HTTP API, from_json turns the response into the types you declared, and to_json writes a request body. Pass from_json the response's text, so a price like 19.99 reaches a Decimal exactly. Passing response.json() would turn it into a float first. Write a field named for a keyword with a trailing _; its JSON key has none:

from dataclasses import dataclassfrom decimal import Decimalfrom flow_toolkit import tool, from_jsonimport httpx@dataclassclass Fare:    class_: str          # the JSON key "class"    price: Decimal    note: str | None = None@tooldef fares(route: str) -> list[Fare]:    response = httpx.get(f"https://fares.example/{route}")    return from_json(list[Fare], response.text)

A value that does not fit fails with the path to it, such as at [2].price: expected a number, found a string.

Give an id its own type, so a program can't pass a customer's id where an order's is wanted. Write it with typing.NewType, assigned to the name it gives. The contract declares a newtype, and at run time the value is still the str it holds:

from typing import NewTypeOrderId = NewType("OrderId", str)"""An order's id."""
/// An order's id.// from payments/__init__.py: OrderIdpub type OrderId(pub Text)
Open snippet in Playground (new tab) ↗

Times are datetime.datetime and datetime.timedelta. A datetime needs a time zone to cross. A time finer than a microsecond, which Python can't hold, doesn't decode, so the call gets no answer instead of a rounded value.

Constructors with fields or none

A @variant dataclass's fields are its constructor's named payload, as Declined { code: Text } above, and a @variant dataclass with no fields is a constructor with no payload. The review in getting-started is written this way:

from dataclasses import dataclassfrom flow_toolkit import tool, variant@variant@dataclassclass Approve:    pass@variant@dataclassclass Revise:    note: str@variant@dataclassclass Decline:    passReview = Approve | Revise | Decline@tooldef review(ticket: str, draft: str) -> Review:    ...

flow build writes pub type Review { Approve, Revise { note: Text }, Decline }, and the Tool returns Revise(note="Mention the refund window") or Approve(). A program matches Revise { note }. A record is still a plain @dataclass; only a union's constructors take @variant.

Write Tools in Rust

Mark each Tool with #[tool], and derive Flow on records, enums and one-field tuple structs, which are newtypes. A function that returns Result<R, flow_toolkit::Problem> declares R, and a Problem is the answer for the call as a whole; any other return type is R whole:

use flow_toolkit::{tool, Context, Flow, Int, Problem};#[derive(Flow)]pub struct AccountId(pub String);/// The balance of an account, in cents, if the account exists.#[tool]pub fn balance(ctx: &Context, account: AccountId) -> Result<Option<Int>, Problem> {    let db = ledger_db().map_err(|e| Problem::NotStarted(e.to_string()))?;    Ok(db.balance(&account.0))}
// Generated by flow build from rust crate ledger. Do not edit.// from src/lib.rs: AccountIdpub type AccountId(pub Text)/// The balance of an account, in cents, if the account exists.// from src/lib.rs: balancepub flow balance(account: AccountId) -> Option<Int>
Open snippet in Playground (new tab) ↗

Use exact types: Int for integers of any size, and an exact decimal type for Decimal. The generator refuses a floating-point type instead of guessing what it meant.

  • A one-field tuple struct that derives Flow is a newtype: struct OrderId(pub String) becomes pub type OrderId(pub Text). A PhantomData field beside it is skipped, so struct Id<T: FlowType>(pub String, PhantomData<T>) becomes pub type Id<T>(pub Text).

  • Visibility follows your Rust. A field that isn't pub is a private field in the contract, and a tuple struct whose field isn't pub has a private constructor. A program can't read a private field or build a value with a private part; it gets such a value only by decoding one, as your Tool's answer, json.decode or a run's input does. Keep a field private when the program has no business making or reading it, such as a token's text. A #[flow(default = Token("t"))] with a private constructor works only on a Tool in the newtype's own module; anywhere else the build refuses it, since the contract couldn't write it.

  • To take or give a std type your code doesn't need to look inside, such as a program's code.Bundle, mark a tuple struct holding a StdValue with the std declaration it is:

    use flow_toolkit::{Flow, StdValue};#[derive(Flow)]#[flow(std = "code.Bundle")]pub struct Bundle(pub StdValue);

    The contract names code.Bundle and imports std@v1/code. Your code holds the value as a flow_toolkit::Value tree, read at std's declaration, and a value it builds is checked against the declaration when it crosses.

  • A default on a newtype parameter is written with its constructor: #[flow(default = OrderId("none"))].

  • Times are std::time::SystemTime and std::time::Duration. A time they can't hold, such as a negative Duration, doesn't decode. flow_toolkit::Duration and flow_toolkit::Instant hold every exact length and instant when a Tool needs them.

  • A Rust module named lib directly under the crate root is refused, because contract/lib.flow is the root module's file.

Run flow build ledger after you change the crate. It builds the library ahead of time, so a run never waits for the build. A run or a check that finds the crate changed since its last build builds it first, and waits for it. The library compiles optimized, in Cargo's release profile: a [profile.release] in the crate's workspace applies, with incremental on unless it says otherwise, so a rebuild after an edit recompiles only what changed. The first build on a machine also compiles the toolkit and its dependencies, once for every Rust library there, and is the slow one.

Write a generic Tool

A Tool can leave a type for the caller to choose. A model call that returns whatever record the program asks for is one: the program writes let plan: Plan = ... and the call's type parameter is Plan. Your code doesn't know Plan, so the call's context tells it. schema is the JSON Schema of the type the caller chose, and decode reads the model's JSON as a value of that type. A value that doesn't fit fails with the reason, which you turn into a value of your declared result, as the model library's extract does:

#[tool]pub fn extract<T: FlowType>(context: &Context, request: Request)    -> Result<Result<Extracted<T>, Error>, Problem> {    let schema = context.schema().ok_or_else(|| Problem::NotStarted("no type to extract".into()))?;    let reply = ask_for_json(&request, schema)?;    Ok(match context.decode::<T>(&reply.value) {        Ok(value) => Ok(Extracted { value, reply }),        Err(error) => Err(Error::InvalidOutput { reason: error.to_string(), reply }),    })}
pub flow extract<T>(request: Request) -> Result<Extracted<T>, Error>
Open snippet in Playground (new tab) ↗

In Python, context().schema is the schema and context().decode(text) reads JSON text, a str or bytes such as the model's reply, and returns the value as plain Python data, Record and Variant objects for records and enums, or raises DecodeError; the type parameter is a TypeVar. Pass the text itself: decode refuses a dict you already parsed. context().to_json(value) writes such a value back as JSON, for when you hand it to a model. A Tool with no type parameter has no schema: schema is None, and decode refuses. So does a Tool with more than one, since neither names which.

Write a library in another language

A library in any language is a process that speaks the Tool process protocol. Name it, and the generator that writes its contract, in a [process] table:

# atlas/flow.toml[process]command = "bin/atlas serve"extract = "bin/atlas extract"

flow build runs extract in the library's root with --library ROOT --out DIR --depfile FILE after its words. It writes each contract module into the empty directory DIR, the root module as lib.flow, and writes the absolute path of each file it read into FILE, one to a line, so the host knows when to run it again. A run starts command in the library's root with --contract FILE, where FILE lists each Tool the run reaches with its identity and type description, which the process sends back to answer describe. Without extract, flow build leaves the committed contract/ as it is, so commit the contract your own tooling writes (The host boundary).

A [process] library gets everything a Python or Rust one does: typed values, host types, holds and replies. A Python or Rust library is a [process] library too: its flow.toml names its toolkit's commands.

Use an MCP server as a library

A library can be any MCP server. Its flow.toml says how to reach it, and flow build lists its tools and writes one declaration for each:

# search/flow.toml[mcp]command = "search-mcp --stdio"

url = "https://..." reaches a server over HTTP instead. flow.toml holds no credential or header. For a server that needs one, name a local bridge in command that reads the secret from its environment. The adapter never holds a call, so wrap a long MCP job in a small Python or Rust library that calls it and holds (The host boundary).

Answer with what you know

Each call gets exactly one answer, and only your code gives it. Pick the one that says what you know:

What happened Answer
The work produced a value, including a failure your domain knows, such as a declined card or a rate limit return it; a domain failure is a value of your return type
You know the work never began, for example a dependency was down before you sent anything raise NotStarted(reason)
The work began and you could not get a value back raise Interrupted(reason)
Your own network to a service failed raise NetworkError(sent=..., reason=...), with sent true if the request may have left
The answer will come later raise Hold() or raise Hold(retry_at=t) (People and webhooks)

In Rust, the same answers are a returned value, or Err(Problem::NotStarted(..)), Err(Problem::Interrupted(..)), Err(Problem::NetworkError { .. }) and Err(Problem::Hold { retry_at }). Problem::hold() and Problem::hold_until(time) write a hold for you.

A held call that is closed without an answer reaches your Tool once more, with context().cancelled set (context.cancelled() in Rust), so it can take the question back (People and webhooks).

Anything else is no answer. An exception you didn't mean as one of these, a value that doesn't encode at your declared type, or a panic leaves the call open and stops the run. A person can then fix the bug and send that one call again (Fix and continue). The toolkit never turns a bug into an answer, and your code shouldn't either: catching every exception and calling it Interrupted tells the program something you don't know.

The call's key, context().key (context.key() in Rust), never changes, even when a person sends the call again after a fix. Pass it to a service as an idempotency key, or use it to recognise a repeat yourself. Its text form, str(key) or the key's Display, is what a webhook hands back to reply.

Set up resources and read the environment

@lifespan (#[lifespan] in Rust) sets up what the process's calls share, such as a client or a connection pool, and cleans it up when the process ends. Read configuration and secrets from the environment there. The host starts the library with the environment of the person who ran flow run or flow resume (the flow command). If a variable is missing, fail in the lifespan: Flow then refuses the run, with your message, before it records anything.

Name a setting your library invents FLOW_LIB_<NAME>_<SETTING>, where <NAME> is the name programs import the library by, upper-cased, with - written as _: the codex library reads FLOW_LIB_CODEX_BINARY. The FLOW_LIB_ prefix tells a reader the variable belongs to a library, not to Flow's own host settings under FLOW_. Two libraries with the same name share the prefix, as they already share a name. A variable that belongs to the service you wrap, such as OPENAI_API_KEY, keeps that service's name.

Keep the contract in step

  • A local library regenerates by itself. When you change a signature, the next flow check, flow run or editor action rewrites contract/ and says what changed. Commit it with the code. Editing only a function's body leaves the contract unchanged, byte for byte.
  • Check it in CI. flow build --check fails if the committed contract differs from what the code would generate.
  • A remote library never regenerates for a program that imports it. Its committed contract is its contract, and binding refuses an implementation that no longer serves it (The host boundary).
  • Share a type by importing it. Declare a type once, in the library that defines it, and import it in other libraries' contracts (Sharing types between libraries).

Test a Tool

Test the native function as native code. The toolkit's testing helpers give a call a context without a run: testing.call(key=...) in Python and Context::for_test in Rust. testing.replies records what your code replied to other calls, and acknowledges each reply as a host would, without one:

from flow_toolkit import Hold, reply, testingdef test_approval_holds_until_the_webhook_replies() -> None:    with testing.call(key="7f3a91c04be2d5e6f708192a3b4c5d6e/root#1") as call:        with pytest.raises(Hold):            approve(refund)    with testing.replies() as sent:        assert reply(call.key, Approval.APPROVE).ok        assert reply(call.key, Approval.APPROVE).same   # a repeat changes nothing    assert sent[0].value is Approval.APPROVE
#[test]fn approval_holds_until_the_webhook_replies() {    let key: CallKey = "7f3a91c04be2d5e6f708192a3b4c5d6e/root#1".parse().unwrap();    assert_eq!(approve(&Context::for_test(key.clone()), refund()), Err(Problem::hold()));    let replies = flow_toolkit::testing::replies();    assert_eq!(flow_toolkit::reply(&key, Approval::Approve), Ok(Ack::Ok));    assert_eq!(replies.sent().len(), 1);}

Run a Python library's tests from its directory with pytest and the toolkit your flow runs, which an installed release keeps under ~/.flow/installations/current and a checkout of Flow under its root:

PYTHONPATH=~/.flow/installations/current/toolkits/python/src \  uv run --no-project --with pytest python -m pytest

In Rust, flow_toolkit::contract! generates the contract of the Tools you list, byte for byte what flow build writes, so a test can compare it with the committed contract/ without the flow command:

#[test]fn the_committed_contract_is_what_the_tools_generate() {    let contract = flow_toolkit::contract!(balance, transfer).unwrap();    for (module, generated) in contract.modules() {        assert_eq!(*generated, contract.committed(module).unwrap(), "{module}");    }}

List every Tool of a module, or that module's generated text won't match its file.

Test the program that uses the library in Flow, with @fake functions standing in for the library's Tools. A fake returns Result<R, ToolProblem>, so a test can produce every Tool problem. A fake that calls test.hold() leaves its call open, so a test can let a deadline win (Running a program).

Exact rules: libraries, what an implementation may say, flow.toml, generated contracts, toolkits, the MCP adapter.