文档

用 Supabase 构建托管工具

你的 Edge Functions 就是 AI 的工具,你的 Postgres 函数决定每个用户能看到和修改什么。无需运行服务器。

如果你的应用运行在 Supabase 上,托管工具需要的东西你已经都有了:Edge Functions 提供公网 HTTPS 端点,Postgres 保存数据和规则。本指南构建一个订单助手:它可以查询用户的订单,并在用户批准后取消订单。

你将构建:

组件运行位置作用
tool_get_order、tool_cancel_orderPostgres 函数AI 能访问的唯一数据,始终按已登录用户过滤
modelriver-toolsEdge Function工具端点。校验 ModelRiver 的签名并调用 Postgres 函数
aiEdge Function由你的应用调用。为已登录用户发起请求,并发送他们的审批决定
聊天组件你的前端使用 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)

你需要一个已通过 Supabase CLI 关联的 Supabase 项目,以及一个已经能回答普通聊天请求的 ModelRiver 工作流。


1. 把工具的数据访问放进 Postgres 函数

ModelRiver 调用的是你的工具端点,而不是用户的浏览器,所以工具函数无法使用用户自己的 Supabase 会话。它使用 service role 密钥,这个密钥会绕过行级安全(RLS)。因此有一条规则必不可少:工具函数从不直接查询表,只调用接收用户 id 并按它过滤的 Postgres 函数。

这样,AI 受到的每一条规则都集中在一个你可以审查的地方,模型只会运行你写好的逻辑。

示例假设有一个类似下面的 orders 表。你可以使用自己的表;关键是有一列把每一行关联到 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);

在迁移中添加工具使用的函数:

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;

用 supabase db push 应用它。

revoke 这几行很重要。没有它们,任何已登录用户都可以在浏览器中用别人的 id 调用 tool_get_order。


2. 创建签名密钥

在 ModelRiver 控制台中打开工作流。在 General 选项卡的 Connect your backend 下,选择 Let the AI call my endpoints,然后打开 Tools 选项卡,在 Tool signing secret 下选择 Create secret。密钥以 mrts_ 开头,只显示一次。

把它和一个项目 API 密钥一起保存为 Edge Function secrets:

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

3. 编写工具端点

一个 Edge Function 服务所有工具。工具名称在签名的请求体中,所以函数按它分发,你为每个工具注册同一个 URL。

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 不会发送 Supabase JWT,所以要为这个函数关闭 Supabase 的 JWT 校验。签名就是它的身份验证:

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

函数的 URL 是 https://<project-ref>.supabase.co/functions/v1/modelriver-tools。

Supabase 正在用 secret 和 publishable 密钥取代 service_role 和 anon 密钥。如果你的项目已经切换到新密钥,请从 SUPABASE_SECRET_KEYS 读取 secret 密钥,代替 SUPABASE_SERVICE_ROLE_KEY;请参见 Supabase 的迁移指南。

为什么 cancel_order 只发送一次也是安全的

会修改数据的工具最多发送一次,从不重试。如果数据库已经提交,而你的函数超时或返回 5xx,模型会被告知结果未知,并且不会再次发送。tool_cancel_order 在与修改相同的事务中按调用 id 保存结果,所以即使同一个调用 id 再次到达,它也只会得到第一次的回答,而不会被取消两次。请参见会修改数据的工具。


4. 注册工具

快捷方式:下载 supabase-order-assistant.workflow.json,并通过 Workflows → Import 导入(请参见导入与导出)。它会创建带有下面两个工具的 order_assistant 工作流。导入前,把 provider 和 model 改为你项目中已连接的提供商和模型,并替换两个 endpoint_url 中的 your-project-ref。导入的工具默认处于关闭状态:在 Tools 选项卡中检查它们,打开工具,然后发布。

如果要手动设置,在工作流的 Tools 选项卡中添加两个工具。两者使用同一个端点 URL。

字段get_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 label正在查询你的订单…正在取消你的订单…
Endpoint URLhttps://<project-ref>.supabase.co/functions/v1/modelriver-tools同上
What does calling it do?Only reads dataChanges something
Approval prompt要取消这个订单吗?此操作无法撤销。
Show to the userorder_number

两者接收相同的参数:

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}

在 get_order 上选择 Send test call,并把 End user id 设为你 Supabase 项目中一个有订单的用户的 id(auth.users.id)。你应该会看到订单数据返回。对 cancel_order 的测试调用会收到函数返回的 403,这说明签名和分发都正常,同时不会取消任何订单。

然后保存并发布工作流。


5. 从 Edge Function 发起请求

你的应用从不持有 ModelRiver API 密钥。第二个 Edge Function 使用用户的 Supabase 会话调用,以该用户作为 end_user 发起请求,并转发他们的审批决定。函数自己用 auth.getUser 校验会话,所以不依赖 Supabase 自带的 verify_jwt 设置。

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 只接受来自发起请求时所用 end_user.id 的决定,所以即使一个用户得知了另一个用户的调用 id,也无法替对方审批。


6. 在应用中显示进度和审批

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 会自动带上已登录用户的会话。问一句"能帮我取消订单 1041 吗?",你会先看到"正在查询你的订单…",然后是审批问题。选择 Cancel order 后,Supabase 中这个订单的行会变为 cancelled,模型也会确认这一点。

一次审批最长可以等待工作流的 Approval wait(默认 10 分钟)。要让页面在长时间等待期间刷新后重新连接,请给 useModelRiver 传入 getToken;请参见重新连接。


安全检查清单

  • 用户 id 两次都来自 Supabase 认证。ai 函数从已校验的 JWT 中取得它,并作为 end_user.id 发送。工具函数从签名的 end_user 中取得它。两者都从不从浏览器的请求体或模型的参数中读取它。
  • 工具只能通过按该 id 过滤的函数访问数据。工具函数中不要出现 db.from('orders')。
  • 这些函数不能从浏览器调用。撤销 anon 和 authenticated 的 execute 权限。
  • 不要把用户的 Supabase 访问令牌放进 end_user.claims。claims 会随请求发送到每一次工具调用,它用于存放套餐或门店 id 之类的事实;而且在调用等待审批期间,Supabase 访问令牌可能会过期。
  • 在生产环境中拒绝 "via": "cli",也不要让 "mode": "test" 的调用修改数据。
  • 工具密钥和 webhook 密钥分开保管。它们使用不同的签名方案;请参见安全。

把回答保存到你的表中

最终回答通过 WebSocket 送达浏览器。如果还想保存它,例如存入一个由 Supabase Realtime 推送到其他设备的 conversations 表,可以添加一个指向 Edge Function 的项目 webhook。Supabase 后端管道指南中有这个函数,包括它的签名校验。

后续步骤

  • 端点契约:每个字段、状态码和限制
  • 审批:审批提示、等待时间,以及被拒绝或过期的调用
  • 测试:Playground 模拟结果,以及用于本地端点的 modelriver tools