---
title: "Ship your agent with your website. Same functions. Same auth. One deploy."
description: "Put the agent in the app it works for. It calls the server functions your pages call, passes the same auth check, and ships in the same build."
---


# Ship your agent with your website. Same functions. Same auth. One deploy.

KinfeMichael Tariku · Nov 2026

Your support team has an order page with a Refund button. Now you want an agent for refund requests: it reads the ticket, looks up the order, and asks a person before any money moves.

The usual setup is a second app. The agent gets its own service, its own database client, its own idea of who may refund what, and its own deploy.

**An agent is one more caller of your app. It should call the functions your pages call, pass the same auth check, and ship in the same build.**

In Farm.js that is a file in `src/agents`, the agent integration, and the `mcp` config from [the last post](/blog/server-functions-as-mcp-tools). This post builds one refund that three callers share: a page, an MCP client, and a durable agent run. Every output below comes from a production build of this code, served with `farm build --preset node-server`.

<span id="two-apps-drift" className="blog-heading-anchor" />

## Two apps drift

A separate agent service starts as a copy of rules your website already has.

- **The logic forks.** The page's refund checks whether the order was already refunded. The agent's refund was written later, against the database, and checks what its author remembered.
- **The auth forks.** People sign in with sessions. The agent service gets one key that may do anything, because carrying a person's permissions across two services is work nobody scheduled.
- **The record forks.** A person approves the refund in the agent's UI, but the agent's key makes the call. The order says the agent refunded it.

None of this is wrong on the first day. It goes wrong the first time someone changes the page and forgets the agent has its own copy.

<span id="same-functions" className="blog-heading-anchor" />

## Same functions

Here are the two functions every caller shares. `withCaller` is the only code that knows who is calling:

```ts
// src/features/orders/server.ts
import { createServerFn, createServerMiddleware } from "@farm.js/core/server-fn";
import { createServerQuery } from "@farm.js/core/server-query";
import { z } from "zod";
import { getCaller } from "../../lib/callers";
import { findOrder, markRefunded } from "../../lib/orders";

const withCaller = createServerMiddleware({
  async handler({ request, next }) {
    const caller = getCaller(request);
    if (!caller) throw new Error("No caller for this request");
    return next({ context: { caller } });
  },
});

export const lookupOrder = createServerQuery({
  key: ({ input }) => ["order", input.orderId],
  input: z.object({ orderId: z.string() }),
  middleware: [withCaller],
  mcp: { name: "lookup_order", description: "Look up an order and whether it was refunded." },
  handler: ({ input }) => findOrder(input.orderId),
});

export const refundOrder = createServerFn({
  input: z.object({ orderId: z.string() }),
  middleware: [withCaller],
  errors: {
    ALREADY_REFUNDED: {
      status: 409,
      message: "This order was already refunded.",
      data: z.object({ refundedBy: z.string() }),
    },
  },
  mcp: { name: "refund_order", description: "Refund an order in full." },
  async handler({ input, context, error }) {
    const order = findOrder(input.orderId);
    if (!order) throw new Error(`No order ${input.orderId}`);
    if (order.refundedBy) return error("ALREADY_REFUNDED", { refundedBy: order.refundedBy });
    return markRefunded(order.id, context.caller.id);
  },
});
```

The agent imports both the way any server code would:

```ts
// src/agents/refund.ts
import { defineAgent } from "agent-unit";
import { lookupOrder, refundOrder } from "../features/orders/server";

export default defineAgent(async (input: { orderId: string }, run) => {
  const order = await run.step("look up order", () => lookupOrder({ orderId: input.orderId }));
  const { approved } = await run.interrupt<{ approved: boolean }>("approve-refund", order);
  if (!approved) return { refunded: false };
  return run.step("refund", () => refundOrder({ orderId: input.orderId }));
});
```

Calling a server function directly on the server runs its whole pipeline: the input schema, `withCaller`, the handler, and the declared errors. It is the same pipeline the page's form runs:

```tsx
// src/app/refund-button.tsx
"use client";
import { useServerFn } from "@farm.js/core/server-fn/client";
import { refundOrder } from "../features/orders/server";

export function RefundButton({ orderId }: { orderId: string }) {
  const refund = useServerFn(refundOrder);
  return (
    <form action={refund.formAction}>
      <input type="hidden" name="orderId" value={orderId} />
      <button type="submit">Refund</button>
      <output>{refund.error ? refund.error.message : refund.status}</output>
    </form>
  );
}
```

`run.step` saves a step when it finishes, so a run that resumes after a restart replays a finished refund instead of calling it again. A step the process died in runs again, so the refund itself has to be safe to repeat: pass the step's `idempotencyKey` to the payment provider, as the [durable agents post](/blog/durable-agents#make-the-real-side-effect-safe-to-repeat) shows.

<span id="same-auth" className="blog-heading-anchor" />

## Same auth

`getCaller` reads a bearer token for agents and a session cookie for people. The config uses it twice more, once for the tools and once for the agent runs:

```ts
// farm.config.ts
import { agent } from "@farm.js/agent";
import { defineConfig } from "@farm.js/core";
import { lookupOrder, refundOrder } from "./src/features/orders/server";
import { getCaller } from "./src/lib/callers";

export default defineConfig({
  experimental: { serverComponents: true, serverActions: true },
  mcp: {
    name: "orders",
    tools: [lookupOrder, refundOrder],
    authorize: ({ request }) => {
      const caller = getCaller(request);
      if (!caller) return false;
      return {
        subject: caller.id,
        tools: caller.kind === "person" ? ["lookup_order", "refund_order"] : ["lookup_order"],
      };
    },
  },
  integrations: {
    agent: agent({
      storage: { driver: "fs-lite", base: ".data/agents" },
      authorize: (request, { action }) => {
        const caller = getCaller(request);
        if (!caller) return false;
        if (action === "resume" || action === "cancel") return caller.kind === "person";
        return true;
      },
    }),
  },
});
```

Agents may look orders up and start runs. Only people may approve or cancel them. Here is what happened when a support agent with a token and Maya, a person with a session, worked on order `o_123`.

The agent listed its tools at `/api/mcp` and got `["lookup_order"]`. It called `refund_order` anyway:

```json
{ "jsonrpc": "2.0", "id": 2, "error": { "code": -32602, "message": "Tool refund_order not found" } }
```

It started the refund agent with `POST /api/agent/agents/refund/runs` and `{"input":{"orderId":"o_123"}}`, and got a `202`. The run looked the order up and stopped at `approve-refund`, with the order as the payload. The agent then tried to approve its own run with `POST /api/agent/runs/:id/resume`:

```json
{ "error": { "code": "unauthorized", "message": "Unauthorized." } }
```

Maya sent the same request with her session cookie and got a `202`. The run finished:

```json
{ "id": "o_123", "email": "ada@example.com", "total": 4200, "refundedBy": "maya" }
```

Look at `refundedBy`. The agent started the run, but the refund step ran inside Maya's resume request, so `withCaller` read her cookie. The order names the person who approved the money, and no code passed her ID around.

Then Maya opened the order page and clicked Refund. Same function, same check:

```text
This order was already refunded.
```

A signed-out browser clicking the same button got `Server function failed`, the sanitized message, and the reason went to the server log:

```text
[Farm.js] Server action failed: Error: No caller for this request
```

<span id="one-deploy" className="blog-heading-anchor" />

## One deploy

`farm build` produced one `.farm/.output` with one server. The page at `/`, the tools at `/api/mcp`, and the runs at `/api/agent` all came from that one process.

I stopped the server while the run waited for approval and started it again. The run was still `interrupted` on `approve-refund`, and Maya's approval after the restart is the one that finished it above. Runs live in the integration's `storage`, which is a local directory here. For more than one instance, [pick shared storage](/docs/integrations/agent#storage-and-deploy-targets).

One deploy also means one version. The agent's `refundOrder` and the page's `refundOrder` are the same code from the same commit, so a schema change can't reach one and miss the other.

<span id="approve-from-the-order-page" className="blog-heading-anchor" />

## Approve from the order page

The agent API is a set of ordinary routes, so the website can be the approvals inbox. The typed client from `agent-unit/client` lists the runs waiting on a person and answers them:

```tsx
// src/app/approvals.tsx
"use client";
import { createAgentClient, type RunRecord } from "agent-unit/client";
import { useEffect, useState } from "react";

const agents = createAgentClient({ baseUrl: "/api/agent" });

export function Approvals() {
  const [waiting, setWaiting] = useState<RunRecord[]>([]);
  const [result, setResult] = useState<unknown>();

  useEffect(() => {
    agents.list({ agent: "refund", status: "interrupted" }).then(setWaiting);
  }, []);

  async function approve(runId: string) {
    for await (const event of agents.resume(runId, { approved: true })) {
      if (event.type === "RUN_FINISHED") setResult(event.result);
    }
    setWaiting((runs) => runs.filter((run) => run.id !== runId));
  }

  return (
    <section>
      {waiting.map((run) => (
        <button key={run.id} onClick={() => approve(run.id)}>
          Approve refund for {(run.input as { orderId: string }).orderId}
        </button>
      ))}
      {result ? <output>{JSON.stringify(result)}</output> : null}
    </section>
  );
}
```

Render `<Approvals />` on the order page. When the support agent started a run, Maya saw one button, `Approve refund for o_123`. One click resumed the run and streamed its events back, and `RUN_FINISHED` carried the result:

```json
{ "id": "o_123", "email": "ada@example.com", "total": 4200, "refundedBy": "maya" }
```

Nothing changed on the server. The browser sends Maya's cookie with `list` and `resume`, so the same `authorize` let her answer and the same `withCaller` recorded her. A signed-out browser got `AgentClientError: Unauthorized.` from `agents.list`.

`agents.events(runId)` follows a run someone else started. From Maya's client, a run the support agent started streamed `RUN_STARTED`, its `look up order` step, and `RUN_INTERRUPTED`, so the page can show what the agent did before it asks.

<span id="give-the-approval-a-deadline" className="blog-heading-anchor" />

## Give the approval a deadline

A refund nobody answers shouldn't wait forever. Give the interrupt a `timeout` and decide what no answer means:

```ts
// src/agents/refund.ts
import { defineAgent } from "agent-unit";
import { InterruptTimeoutError } from "agent-unit/runtime";
import { lookupOrder, refundOrder } from "../features/orders/server";

export default defineAgent(async (input: { orderId: string }, run) => {
  const order = await run.step("look up order", () => lookupOrder({ orderId: input.orderId }));
  const { approved } = await run
    .interrupt<{ approved: boolean }>("approve-refund", order, { timeout: "24h" })
    .catch((error) => {
      if (error instanceof InterruptTimeoutError) return { approved: false };
      throw error;
    });
  if (!approved) return { refunded: false };
  return run.step("refund", () => refundOrder({ orderId: input.orderId }));
});
```

I ran this with `timeout: "3s"` and didn't answer. The run showed `interrupted` with `interrupt.expiresAt` set, then finished three seconds later with `{"refunded":false}`. `refundOrder` never ran.

The deadline is stored with the run. I stopped the server before a run's deadline and started it again after. The run stayed `interrupted` until agent-unit's scheduled sweep came round, 45 seconds later, and then finished the same way.

The agent API has two more pieces that fit this flow, both in the [agent docs](/docs/integrations/agent#wait-for-an-external-event). `run.waitFor` parks a run until an event arrives at `POST /api/agent/events`, such as the payment provider confirming the refund, and `authorize` sees `action: "send"` with the event's name. A task with `agent` starts runs on a schedule, such as a morning digest of refunds still waiting.

<span id="try-it" className="blog-heading-anchor" />

## Try it

```bash
pnpm add @farm.js/agent agent-unit @farm.js/mcp
```

Put your session and token checks in one `getCaller`, give a server function an `mcp` name, and write an agent in `src/agents` that imports the function. Then start a run as an agent, and approve it from the page as a person.

[Agent integration](/docs/integrations/agent) · [Server functions as MCP tools](/docs/plugins/mcp#server-functions-and-queries) · [Durable agents](/blog/durable-agents) · [Your server functions are already MCP tools](/blog/server-functions-as-mcp-tools)

The agent doesn't need its own copy of your app. It needs a way in, and your app already has one.
