Documentation

Hosted tools with Supabase

Your Edge Functions become the AI's tools. Your Postgres functions decide what each user may see and change. No server to run.

If your app runs on Supabase, you already have everything a hosted tool needs: Edge Functions give you public HTTPS endpoints, and Postgres holds the data and the rules. This guide builds an order assistant that can look up a user's order and, after the user approves, cancel it.

What you'll build:

PieceWhere it runsWhat it does
tool_get_order, tool_cancel_orderPostgres functionsThe only data the AI can reach, always filtered by the signed-in user
modelriver-toolsEdge FunctionThe tool endpoint. Checks ModelRiver's signature and calls the Postgres functions
aiEdge FunctionCalled by your app. Starts a request for the signed-in user and sends their approvals
The chat componentYour frontendShows progress and the approval question with the Client SDK
TEXT
1Browser ──supabase.functions.invoke('ai')──► ai (Edge Function) ──► ModelRiver
2 ▲ │
3 └──────────── progress, approvals, answer (WebSocket) ◄─────────────┤
4 ▼
5 modelriver-tools (Edge Function) ◄── signed tool calls
6 │
7 ▼
8 tool_get_order / tool_cancel_order (Postgres)

You need a Supabase project with the Supabase CLI linked to it, and a ModelRiver workflow that answers plain chat requests.


1. Put the tools' data access in Postgres functions

ModelRiver calls your tool endpoint, not your user's browser, so the tool function can't act with the user's own Supabase session. It uses the service role key, which skips row-level security. That makes one rule essential: the tool function never queries tables directly. It calls Postgres functions that take the user id and filter by it.

This keeps every rule the AI is held to in one place you can review, and the model only ever runs logic you wrote.

The example assumes an orders table like this one. Use your own; what matters is a column that ties each row to auth.users:

SQL
1create table public.orders (
2 id bigint generated always as identity primary key,
3 number text not null unique,
4 user_id uuid not null references auth.users (id),
5 status text not null default 'placed', -- placed, shipped, delivered, cancelled
6 total numeric(10, 2) not null,
7 currency text not null default 'USD',
8 item_count int not null,
9 created_at timestamptz not null default now(),
10 cancelled_at timestamptz
11);

Add the tools' functions in a migration:

SQL
1-- supabase/migrations/20261118000000_modelriver_tools.sql
2 
3-- Results of tool calls that changed something, by ModelRiver call id,
4-- so the same call is never applied twice.
5create table public.tool_calls (
6 call_id text primary key,
7 user_id uuid not null,
8 result jsonb not null,
9 created_at timestamptz not null default now()
10);
11 
12-- RLS on with no policies: only the service role can read or write it.
13alter table public.tool_calls enable row level security;
14 
15create or replace function public.tool_get_order(p_user_id uuid, p_order_number text)
16returns jsonb
17language sql
18stable
19set search_path = ''
20as $$
21 select jsonb_build_object(
22 'order_number', o.number,
23 'status', o.status,
24 'total', o.total,
25 'currency', o.currency,
26 'placed_at', o.created_at,
27 'item_count', o.item_count
28 )
29 from public.orders o
30 where o.number = p_order_number
31 and o.user_id = p_user_id;
32$$;
33 
34create or replace function public.tool_cancel_order(p_user_id uuid, p_order_number text, p_call_id text)
35returns jsonb
36language plpgsql
37set search_path = ''
38as $$
39declare
40 v_done jsonb;
41 v_status text;
42 v_result jsonb;
43begin
44 -- The same call id again: answer with what was done the first time.
45 select result into v_done from public.tool_calls where call_id = p_call_id;
46 if found then
47 return v_done;
48 end if;
49 
50 select status into v_status
51 from public.orders
52 where number = p_order_number and user_id = p_user_id
53 for update;
54 
55 if not found then
56 v_result := jsonb_build_object('error', 'not_found');
57 elsif v_status <> 'placed' then
58 v_result := jsonb_build_object('error', 'not_cancellable', 'status', v_status);
59 else
60 update public.orders
61 set status = 'cancelled', cancelled_at = now()
62 where number = p_order_number and user_id = p_user_id;
63 v_result := jsonb_build_object('order_number', p_order_number, 'status', 'cancelled');
64 end if;
65 
66 insert into public.tool_calls (call_id, user_id, result)
67 values (p_call_id, p_user_id, v_result)
68 on conflict (call_id) do nothing;
69 
70 return v_result;
71end;
72$$;
73 
74-- Supabase exposes public functions to the browser through its API by default.
75-- These take a user id as an argument, so only the service role may run them.
76revoke execute on function public.tool_get_order(uuid, text) from public, anon, authenticated;
77revoke execute on function public.tool_cancel_order(uuid, text, text) from public, anon, authenticated;
78grant execute on function public.tool_get_order(uuid, text) to service_role;
79grant execute on function public.tool_cancel_order(uuid, text, text) to service_role;

Apply it with supabase db push.

The revoke lines matter. Without them, any signed-in user could call tool_get_order from the browser with someone else's id.


2. Create the signing secret

Open the workflow in the ModelRiver console. On the General tab, under Connect your backend, choose Let the AI call my endpoints, then open the Tools tab and select Create secret under Tool signing secret. It starts with mrts_ and is shown once.

Store it, with a project API key, as Edge Function secrets:

Bash
supabase secrets set MODELRIVER_TOOL_SECRET=mrts_... MODELRIVER_API_KEY=mr_live_...

3. Write the tool endpoint

One Edge Function serves every tool. The tool's name is inside the signed body, so the function routes on it and you register the same URL for each tool.

TYPESCRIPT
1// supabase/functions/modelriver-tools/index.ts
2import { createClient } from 'npm:@supabase/supabase-js@2';
3 
4// While you rotate the secret, list the new one as well: either is accepted.
5const SECRETS = [Deno.env.get('MODELRIVER_TOOL_SECRET') ?? ''];
6 
7const db = createClient(
8 Deno.env.get('SUPABASE_URL')!,
9 Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
10 { auth: { persistSession: false } },
11);
12 
13const encoder = new TextEncoder();
14const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
15 
16function hexToBytes(hex: string): Uint8Array | null {
17 if (!/^[0-9a-f]{64}$/.test(hex)) return null;
18 const bytes = new Uint8Array(32);
19 for (let i = 0; i < 32; i++) bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
20 return bytes;
21}
22 
23// Checks x-modelriver-signature: v2=hex(HMAC-SHA256(secret, "v2.<timestamp>.<call id>.<raw body>"))
24async function verifyToolCall(body: Uint8Array, headers: Headers, secrets: string[], toleranceSeconds = 300) {
25 const timestamp = headers.get('x-modelriver-timestamp') ?? '';
26 const callId = headers.get('x-modelriver-tool-call-id') ?? '';
27 const signatures = (headers.get('x-modelriver-signature') ?? '')
28 .split(',')
29 .map((part) => part.trim())
30 .filter((part) => part.startsWith('v2='))
31 .map((part) => hexToBytes(part.slice(3)))
32 .filter((bytes): bytes is Uint8Array => bytes !== null);
33 
34 if (!/^\d+$/.test(timestamp) || !callId || signatures.length === 0) return false;
35 if (Math.abs(Date.now() / 1000 - Number(timestamp)) > toleranceSeconds) return false;
36 
37 const prefix = encoder.encode(`v2.${timestamp}.${callId}.`);
38 const signed = new Uint8Array(prefix.length + body.length);
39 signed.set(prefix);
40 signed.set(body, prefix.length);
41 
42 for (const secret of secrets.filter(Boolean)) {
43 const key = await crypto.subtle.importKey(
44 'raw', encoder.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['verify'],
45 );
46 // crypto.subtle.verify compares in constant time
47 for (const signature of signatures) {
48 if (await crypto.subtle.verify('HMAC', key, signature, signed)) return true;
49 }
50 }
51 return false;
52}
53 
54const json = (body: unknown, status = 200) =>
55 new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
56 
57const refuse = (status: number, message: string, userMessage?: string) =>
58 json({ error: { message, ...(userMessage ? { user_message: userMessage } : {}) } }, status);
59 
60Deno.serve(async (req) => {
61 if (req.method !== 'POST') return new Response('Method not allowed', { status: 405 });
62 
63 // Read the exact bytes ModelRiver signed. Don't parse and re-encode before checking.
64 const body = new Uint8Array(await req.arrayBuffer());
65 if (!(await verifyToolCall(body, req.headers, SECRETS))) return refuse(401, 'Bad signature');
66 
67 const call = JSON.parse(new TextDecoder().decode(body));
68 
69 // A call forwarded to a developer's machine by `modelriver tools` must never reach production data.
70 if (call.request?.via === 'cli') return refuse(403, 'CLI calls are not accepted here');
71 
72 // Who is asking comes from end_user, which your `ai` function sent and ModelRiver signed.
73 // Never take it from call.arguments: the model wrote those.
74 const userId = call.end_user?.id;
75 if (typeof userId !== 'string' || !UUID.test(userId)) return refuse(400, 'end_user.id must be a Supabase user id');
76 
77 switch (call.tool) {
78 case 'get_order': {
79 const { data, error } = await db.rpc('tool_get_order', {
80 p_user_id: userId,
81 p_order_number: call.arguments.order_number,
82 });
83 if (error) return refuse(500, 'Lookup failed');
84 if (!data) return refuse(404, 'No order with that number for this user', "I couldn't find that order.");
85 return json(data);
86 }
87 
88 case 'cancel_order': {
89 // A console test call is signed like a real one. Don't let it cancel anything.
90 if (call.request.mode === 'test') return refuse(403, 'Test calls do not cancel orders');
91 
92 const { data, error } = await db.rpc('tool_cancel_order', {
93 p_user_id: userId,
94 p_order_number: call.arguments.order_number,
95 p_call_id: call.id,
96 });
97 if (error) return refuse(500, 'Cancel failed');
98 if (data.error === 'not_found') return refuse(404, 'No order with that number for this user', "I couldn't find that order.");
99 if (data.error === 'not_cancellable') {
100 return refuse(409, `Order is ${data.status} and can't be cancelled`, `That order is already ${data.status}.`);
101 }
102 return json(data);
103 }
104 
105 default:
106 return refuse(404, `Unknown tool ${call.tool}`);
107 }
108});

ModelRiver doesn't send a Supabase JWT, so turn off Supabase's JWT check for this function. The signature is its authentication:

TOML
1# supabase/config.toml
2[functions.modelriver-tools]
3verify_jwt = false
Bash
supabase functions deploy modelriver-tools --no-verify-jwt

The function's URL is https://<project-ref>.supabase.co/functions/v1/modelriver-tools.

Supabase is replacing the service_role and anon keys with secret and publishable keys. If your project has moved to the new keys, read the secret key from SUPABASE_SECRET_KEYS in place of SUPABASE_SERVICE_ROLE_KEY; see Supabase's migration guide.

Why cancel_order is safe to send once

A tool that changes something is sent at most once and never retried. If your function times out or answers 5xx after the database committed, the model is told the outcome is unknown, and nothing is sent again. tool_cancel_order stores the result under the call's id inside the same transaction as the change, so if the same call id ever does arrive again, it gets the first answer back instead of a second cancellation. See Tools that change something.


4. Register the tools

The quick way: download supabase-order-assistant.workflow.json and bring it in with Workflows → Import (see Import and export). It creates the order_assistant workflow with both tools below. Before you import, set provider and model to ones connected in your project, and replace your-project-ref in both endpoint_url values. Imported tools arrive switched off: review them on the Tools tab, switch tools on, and publish.

To set them up by hand, add two tools on the workflow's Tools tab. Both use the same endpoint URL.

Fieldget_ordercancel_order
Description for the modelLooks up one of the signed-in user's orders by its order number: status, total, when it was placed and how many items it has.Cancels one of the signed-in user's orders by its order number. Only orders that haven't shipped can be cancelled. Look the order up first.
Progress labelLooking up your order…Cancelling your order…
Endpoint URLhttps://<project-ref>.supabase.co/functions/v1/modelriver-toolsthe same
What does calling it do?Only reads dataChanges something
Approval promptCancel this order? This can't be undone.
Show to the userorder_number

Both take the same arguments:

JSON
1{
2 "type": "object",
3 "properties": {
4 "order_number": { "type": "string", "description": "The order number, for example 1041" }
5 },
6 "required": ["order_number"],
7 "additionalProperties": false
8}

Select Send test call on get_order, with End user id set to the id of a user in your Supabase project (auth.users.id) who has an order. You should see the order come back. A test call to cancel_order returns the 403 from the function, which shows the signature and routing work without cancelling anything.

Then save and publish the workflow.


5. Start requests from an Edge Function

Your app never holds the ModelRiver API key. A second Edge Function, called with the user's Supabase session, starts the request with that user as end_user and forwards their approvals. The function checks the session itself with auth.getUser, so it doesn't rely on Supabase's own verify_jwt setting.

TYPESCRIPT
1// supabase/functions/ai/index.ts
2import { createClient } from 'npm:@supabase/supabase-js@2';
3 
4const MODELRIVER = 'https://api.modelriver.com';
5const API_KEY = Deno.env.get('MODELRIVER_API_KEY')!;
6 
7const supabase = createClient(Deno.env.get('SUPABASE_URL')!, Deno.env.get('SUPABASE_ANON_KEY')!);
8 
9const cors = {
10 'Access-Control-Allow-Origin': '*', // set this to your app's origin
11 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
12};
13 
14const reply = (body: unknown, status = 200) =>
15 new Response(JSON.stringify(body), { status, headers: { ...cors, 'Content-Type': 'application/json' } });
16 
17const modelriver = (path: string, body: unknown) =>
18 fetch(`${MODELRIVER}${path}`, {
19 method: 'POST',
20 headers: { Authorization: `Bearer ${API_KEY}`, 'Content-Type': 'application/json' },
21 body: JSON.stringify(body),
22 });
23 
24Deno.serve(async (req) => {
25 if (req.method === 'OPTIONS') return new Response('ok', { headers: cors });
26 
27 const jwt = (req.headers.get('Authorization') ?? '').replace(/^Bearer /, '');
28 const { data: { user } } = await supabase.auth.getUser(jwt);
29 if (!user) return reply({ error: 'Not signed in' }, 401);
30 
31 const input = await req.json();
32 
33 if (input.action === 'start') {
34 const res = await modelriver('/v1/ai/async', {
35 workflow: 'order_assistant',
36 messages: [{ role: 'user', content: String(input.message ?? '') }],
37 // The id comes from the verified session, never from the browser.
38 end_user: { id: user.id },
39 });
40 const ticket = await res.json();
41 if (!res.ok) return reply({ error: 'Could not start the request' }, 502);
42 
43 const { channel_id, ws_token, websocket_url, websocket_channel } = ticket;
44 return reply({ channel_id, ws_token, websocket_url, websocket_channel });
45 }
46 
47 if (input.action === 'approve' || input.action === 'reject') {
48 const callId = encodeURIComponent(String(input.call_id ?? ''));
49 const res = await modelriver(`/v1/ai/tool-calls/${callId}/${input.action}`, {
50 end_user: { id: user.id },
51 });
52 return reply(await res.json(), res.status);
53 }
54 
55 return reply({ error: 'Unknown action' }, 400);
56});
Bash
supabase functions deploy ai

ModelRiver accepts a decision only from the end_user.id the request was sent with, so one user can't approve another user's call even if they learn its id.


6. Show progress and approvals in your app

TSX
1import { useModelRiver } from '@modelriver/client/react';
2import { supabase } from './supabase';
3 
4export function OrderAssistant() {
5 const { connect, toolCalls, pendingApprovals, response, error } = useModelRiver();
6 
7 async function ask(message: string) {
8 const { data, error: invokeError } = await supabase.functions.invoke('ai', { body: { action: 'start', message } });
9 if (invokeError) throw invokeError;
10 connect({
11 channelId: data.channel_id,
12 wsToken: data.ws_token,
13 websocketUrl: data.websocket_url,
14 websocketChannel: data.websocket_channel,
15 });
16 }
17 
18 const decide = (callId: string, action: 'approve' | 'reject') =>
19 supabase.functions.invoke('ai', { body: { action, call_id: callId } });
20 
21 return (
22 <div>
23 {toolCalls.map((call) => (
24 <p key={call.id}>{call.label ?? call.name}{call.status === 'running' ? '' : ' ✓'}</p>
25 ))}
26 
27 {pendingApprovals.map((approval) => (
28 <div key={approval.id}>
29 {/* Plain text only: the arguments were written by the model */}
30 <p>{approval.prompt}</p>
31 <p>Order {String(approval.arguments.order_number)}</p>
32 <button onClick={() => decide(approval.id, 'approve')}>Cancel order</button>
33 <button onClick={() => decide(approval.id, 'reject')}>Keep it</button>
34 </div>
35 ))}
36 
37 {response?.status === 'success' && <pre>{JSON.stringify(response.data, null, 2)}</pre>}
38 {error && <p>{error}</p>}
39 </div>
40 );
41}

supabase.functions.invoke sends the signed-in user's session for you. Ask "Can you cancel order 1041?" and you'll see "Looking up your order…", then the approval question. After Cancel order, the order's row in Supabase changes to cancelled and the model confirms it.

An approval can wait up to the workflow's Approval wait (10 minutes by default). To let the page rejoin after a reload during a long wait, pass getToken to useModelRiver; see Reconnecting.


Security checklist

  • The user id comes from Supabase auth, twice. The ai function takes it from the verified JWT and sends it as end_user.id. The tool function takes it from the signed end_user. Neither ever reads it from the browser's body or the model's arguments.
  • Tools reach data only through functions that filter by that id. No db.from('orders') in the tool function.
  • Those functions can't be called from the browser. Revoke execute from anon and authenticated.
  • Don't put the user's Supabase access token in end_user.claims. Claims travel with the request to every tool call, are meant for facts such as a plan or a store id, and a Supabase access token can expire while a call waits for approval.
  • Refuse "via": "cli" in production, and don't let "mode": "test" calls change data.
  • Keep the tool secret and the webhook secret apart. They use different schemes; see Security.

Saving answers to your tables

The final answer reaches the browser over the WebSocket. To also store it, for example in a conversations table that Supabase Realtime pushes to other devices, add a project webhook pointing at an Edge Function. The Supabase backend pipeline guide has that function, including its signature check.

Next steps

  • Endpoint contract: every field, status code and limit
  • Approvals: approval prompts, waits, and declined or expired calls
  • Testing: Playground mock results and modelriver tools for local endpoints