# Build a workflow

Chain steps in one workflow file, each running code, a tool or an agent, so each step's result feeds the next.

## Before you start

You need a project. See [Create a project](/docs/projects/create-project.md).

## Build a workflow

**Studio**

1. In your project, open **Building blocks** > **Workflows**.

2. Click **Create workflow**.

3. Enter `split-bill` as the **Name**.

4. Enter `Add a tip to a bill and split it between people.` as the **Description**.

5. Replace the **Source code** with:

   ```ts
   import { tool } from "veryfront/tool";
   import { step, workflow } from "veryfront/workflow";

   type Bill = { bill: number; tip: number; people: number };

   const addTip = tool({
     id: "add-tip",
     description: "Add a tip, in percent, to a bill.",
     inputSchema: {
       type: "object",
       properties: { bill: { type: "number" }, tip: { type: "number" } },
       required: ["bill", "tip"],
       additionalProperties: false,
     },
     execute: async ({ bill, tip }) => ({ total: Math.round(bill * (1 + tip / 100) * 100) / 100 }),
   });

   const splitEvenly = tool({
     id: "split-evenly",
     description: "Split a total between people.",
     inputSchema: {
       type: "object",
       properties: { total: { type: "number" }, people: { type: "number" } },
       required: ["total", "people"],
       additionalProperties: false,
     },
     execute: async ({ total, people }) => ({ share: Math.round((total / people) * 100) / 100 }),
   });

   export default workflow({
     id: "split-bill",
     description: "Add a tip to a bill and split it between people.",
     steps: [
       step("add-tip", {
         tool: addTip,
         input: (ctx) => {
           const { bill, tip } = ctx.input as Bill;
           return { bill, tip };
         },
       }),
       step("split", {
         tool: splitEvenly,
         input: (ctx) => ({
           total: (ctx["add-tip"] as { total: number }).total,
           people: (ctx.input as Bill).people,
         }),
       }),
     ],
   });
   ```

6. Click **Create workflow**.

7. Open the **⋯** menu.

8. Click **Run workflow**.

9. Paste the **Payload**:

   ```json
   { "bill": 84.5, "tip": 18, "people": 3 }
   ```

10. Click **Create run**. You should now see the run **Completed**, with `"share": 33.24` in its **Output**.

**Code**

1. Add the workflow. Each step names a tool and builds its input from the run's `input` or an earlier step's result:

```ts title="workflows/split-bill.ts"
import { tool } from "veryfront/tool";
import { step, workflow } from "veryfront/workflow";

type Bill = { bill: number; tip: number; people: number };

const addTip = tool({
  id: "add-tip",
  description: "Add a tip, in percent, to a bill.",
  inputSchema: {
    type: "object",
    properties: { bill: { type: "number" }, tip: { type: "number" } },
    required: ["bill", "tip"],
    additionalProperties: false,
  },
  execute: async ({ bill, tip }) => ({ total: Math.round(bill * (1 + tip / 100) * 100) / 100 }),
});

const splitEvenly = tool({
  id: "split-evenly",
  description: "Split a total between people.",
  inputSchema: {
    type: "object",
    properties: { total: { type: "number" }, people: { type: "number" } },
    required: ["total", "people"],
    additionalProperties: false,
  },
  execute: async ({ total, people }) => ({ share: Math.round((total / people) * 100) / 100 }),
});

export default workflow({
  id: "split-bill",
  description: "Add a tip to a bill and split it between people.",
  steps: [
    step("add-tip", {
      tool: addTip,
      input: (ctx) => {
        const { bill, tip } = ctx.input as Bill;
        return { bill, tip };
      },
    }),
    step("split", {
      tool: splitEvenly,
      input: (ctx) => ({
        total: (ctx["add-tip"] as { total: number }).total,
        people: (ctx.input as Bill).people,
      }),
    }),
  ],
});
```

2. Run it on your machine. `--input` is the run's input:

```bash
npx veryfront workflow run split-bill --input '{"bill": 84.5, "tip": 18, "people": 3}'
```

3. Read the result: it prints `"share": 33.24`.
4. Start the project with `npm run dev` ([Work locally](/docs/projects/local.md)) and open **Building blocks** > **Workflows** in Studio. You should now see `split-bill` listed.

### Try it in a sandbox

```playground
step: Create a project | npm create -y veryfront@latest bill-splitter -- --template ai-agent --yes
step: Add the workflow | cd bill-splitter && mkdir -p workflows && printf '%s\n' 'import { tool } from "veryfront/tool";' 'import { step, workflow } from "veryfront/workflow";' '' 'type Bill = { bill: number; tip: number; people: number };' '' 'const addTip = tool({' '  id: "add-tip",' '  description: "Add a tip, in percent, to a bill.",' '  inputSchema: {' '    type: "object",' '    properties: { bill: { type: "number" }, tip: { type: "number" } },' '    required: ["bill", "tip"],' '    additionalProperties: false,' '  },' '  execute: async ({ bill, tip }) => ({ total: Math.round(bill * (1 + tip / 100) * 100) / 100 }),' '});' '' 'const splitEvenly = tool({' '  id: "split-evenly",' '  description: "Split a total between people.",' '  inputSchema: {' '    type: "object",' '    properties: { total: { type: "number" }, people: { type: "number" } },' '    required: ["total", "people"],' '    additionalProperties: false,' '  },' '  execute: async ({ total, people }) => ({ share: Math.round((total / people) * 100) / 100 }),' '});' '' 'export default workflow({' '  id: "split-bill",' '  description: "Add a tip to a bill and split it between people.",' '  steps: [' '    step("add-tip", {' '      tool: addTip,' '      input: (ctx) => {' '        const { bill, tip } = ctx.input as Bill;' '        return { bill, tip };' '      },' '    }),' '    step("split", {' '      tool: splitEvenly,' '      input: (ctx) => ({' '        total: (ctx["add-tip"] as { total: number }).total,' '        people: (ctx.input as Bill).people,' '      }),' '    }),' '  ],' '});' > workflows/split-bill.ts
check: npx veryfront workflow run split-bill --input '{"bill": 84.5, "tip": 18, "people": 3}'
expect: "share": 33.24
```

**API**

1. Set `PROJECT` to your project's ID ([Find your IDs](/docs/authentication/api-keys.md#find-your-ids)): `export PROJECT=<id>`.
2. Save the workflow's source as `split-bill.ts`, the file in the **Code** tab's step 1.
3. Write it to `workflows/split-bill.ts` with your [API key](/docs/authentication/api-keys.md). `jq` sends it as `content`; `%2F` is the `/`:

```bash
jq -n --rawfile content split-bill.ts '{content: $content}' | \
  curl -X PUT https://api.veryfront.com/projects/$PROJECT/files/workflows%2Fsplit-bill.ts \
  -H "Authorization: Bearer $VERYFRONT_API_KEY" \
  -H "Content-Type: application/json" \
  --data-binary @-
```

4. List the workflows. You should now see `split-bill`:

```bash
curl https://api.veryfront.com/projects/$PROJECT/workflows \
  -H "Authorization: Bearer $VERYFRONT_API_KEY"
```

5. Get the project. A run takes its `id`, not the slug:

```bash
curl https://api.veryfront.com/projects/$PROJECT \
  -H "Authorization: Bearer $VERYFRONT_API_KEY"
```

6. Set `PROJECT_ID` to the `id` in the response: `export PROJECT_ID=<id>`.
7. Run the workflow with the input:

```bash
curl -X POST https://api.veryfront.com/runs \
  -H "Authorization: Bearer $VERYFRONT_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: split-bill-1" \
  -d '{
    "project_id": "'$PROJECT_ID'",
    "target": { "type": "workflow", "id": "split-bill" },
    "input": { "bill": 84.5, "tip": 18, "people": 3 }
  }'
```

8. Set `RUN_ID` to the `run_id` in the response: `export RUN_ID=<run_id>`.
9. Read the run until `status` is `completed`. You should now see `"share": 33.24` in `output`:

```bash
curl https://api.veryfront.com/runs/$RUN_ID \
  -H "Authorization: Bearer $VERYFRONT_API_KEY"
```

### Try it in a sandbox

```playground
step: Set PROJECT | export PROJECT=$VERYFRONT_PROJECT_ID
step: Save the workflow's source as split-bill.ts | printf '%s\n' 'import { tool } from "veryfront/tool";' 'import { step, workflow } from "veryfront/workflow";' '' 'type Bill = { bill: number; tip: number; people: number };' '' 'const addTip = tool({' '  id: "add-tip",' '  description: "Add a tip, in percent, to a bill.",' '  inputSchema: {' '    type: "object",' '    properties: { bill: { type: "number" }, tip: { type: "number" } },' '    required: ["bill", "tip"],' '    additionalProperties: false,' '  },' '  execute: async ({ bill, tip }) => ({ total: Math.round(bill * (1 + tip / 100) * 100) / 100 }),' '});' '' 'const splitEvenly = tool({' '  id: "split-evenly",' '  description: "Split a total between people.",' '  inputSchema: {' '    type: "object",' '    properties: { total: { type: "number" }, people: { type: "number" } },' '    required: ["total", "people"],' '    additionalProperties: false,' '  },' '  execute: async ({ total, people }) => ({ share: Math.round((total / people) * 100) / 100 }),' '});' '' 'export default workflow({' '  id: "split-bill",' '  description: "Add a tip to a bill and split it between people.",' '  steps: [' '    step("add-tip", {' '      tool: addTip,' '      input: (ctx) => {' '        const { bill, tip } = ctx.input as Bill;' '        return { bill, tip };' '      },' '    }),' '    step("split", {' '      tool: splitEvenly,' '      input: (ctx) => ({' '        total: (ctx["add-tip"] as { total: number }).total,' '        people: (ctx.input as Bill).people,' '      }),' '    }),' '  ],' '});' > split-bill.ts
step: Write it to workflows/split-bill.ts | jq -n --rawfile content split-bill.ts '{content: $content}' | curl -X PUT https://api.veryfront.com/projects/$PROJECT/files/workflows%2Fsplit-bill.ts -H "Authorization: Bearer $VERYFRONT_API_KEY" -H "Content-Type: application/json" --data-binary @-
step: List the workflows | curl https://api.veryfront.com/projects/$PROJECT/workflows -H "Authorization: Bearer $VERYFRONT_API_KEY"
step: Get the project | curl https://api.veryfront.com/projects/$PROJECT -H "Authorization: Bearer $VERYFRONT_API_KEY"
step: Set PROJECT_ID | export PROJECT_ID=$(curl -s https://api.veryfront.com/projects/$PROJECT -H "Authorization: Bearer $VERYFRONT_API_KEY" | jq -r .id)
step: Run the workflow | curl -X POST https://api.veryfront.com/runs -H "Authorization: Bearer $VERYFRONT_API_KEY" -H "Content-Type: application/json" -H "Idempotency-Key: split-bill-1" -d '{ "project_id": "'$PROJECT_ID'", "target": { "type": "workflow", "id": "split-bill" }, "input": { "bill": 84.5, "tip": 18, "people": 3 } }' | tee run.json
step: Set RUN_ID | export RUN_ID=$(jq -r .run_id run.json)
step: Wait until it is completed | until [ "$(curl -s https://api.veryfront.com/runs/$RUN_ID -H "Authorization: Bearer $VERYFRONT_API_KEY" | jq -r .status)" = completed ]; do sleep 3; done
check: curl https://api.veryfront.com/runs/$RUN_ID -H "Authorization: Bearer $VERYFRONT_API_KEY"
expect: "share":33.24
```

## With MCP

`my-project` stands for your project's reference: its slug or its ID, both in the answer of `veryfront__create_project` or `veryfront__list_projects`.

1. Call `veryfront__create_file` with `"project_reference": "my-project"`, `"path": "workflows/split-bill.ts"` and the workflow's source from the Code tab as `content`.
2. Call `veryfront__list_workflows` with `"project_reference": "my-project"`. It worked when `split-bill` is listed.
3. Call `veryfront__create_run` with the project's `id` (a run takes the ID, not the slug):

```json
{
  "input": {
    "project_id": "<id>",
    "target": { "type": "workflow", "id": "split-bill" },
    "input": { "bill": 84.5, "tip": 18, "people": 3 }
  },
  "idempotency_key": "split-bill-1"
}
```

4. Call `veryfront__get_run` with the returned `run_id` until `status` is `completed`. It worked when `output.split.share` is `33.24`. The output holds each step's result under its name.

## Next steps

* [Add approvals](/docs/orchestration/approvals.md)
* [Schedule a run](/docs/orchestration/schedules.md)
