Documentation

Early access

Your first hosted tool

One endpoint, one tool, one request. About fifteen minutes from an empty Tools tab to an answer built from your own data.

This guide adds one tool, get_sales_summary, to a chat workflow. You need a workflow that already answers plain chat requests, and hosted tools enabled for your organization.

1. Create the signing secret

Open the workflow in the console. On the General tab, under Connect your backend, choose Let the AI call my endpoints, then select the Tools tab. Under Tool signing secret, below the tool list, select Create secret.

The secret starts with mrts_ and is shown once. Copy it into your backend's environment, for example as MODELRIVER_TOOL_SECRET. One secret covers every tool in the project.

2. Write the endpoint

A tool is an HTTPS endpoint that takes a signed POST and returns JSON. This one checks the signature, reads who the request is for, and returns that user's numbers.

Node.js (Express)

JAVASCRIPT
1import crypto from 'node:crypto';
2import express from 'express';
3 
4const app = express();
5const SECRETS = [process.env.MODELRIVER_TOOL_SECRET];
6 
7function verifyToolCall(rawBody, headers, secrets, toleranceSeconds = 300) {
8 const timestamp = headers['x-modelriver-timestamp'];
9 const callId = headers['x-modelriver-tool-call-id'];
10 const signatures = String(headers['x-modelriver-signature'] || '')
11 .split(',')
12 .map((part) => part.trim())
13 .filter((part) => part.startsWith('v2='))
14 .map((part) => part.slice(3));
15 
16 if (!/^\d+$/.test(timestamp || '') || !callId || signatures.length === 0) return false;
17 if (Math.abs(Date.now() / 1000 - Number(timestamp)) > toleranceSeconds) return false;
18 
19 return secrets.some((secret) => {
20 const expected = crypto
21 .createHmac('sha256', secret)
22 .update(`v2.${timestamp}.${callId}.`)
23 .update(rawBody)
24 .digest('hex');
25 const expectedBytes = Buffer.from(expected);
26 
27 return signatures.some((given) => {
28 const givenBytes = Buffer.from(given);
29 return givenBytes.length === expectedBytes.length && crypto.timingSafeEqual(givenBytes, expectedBytes);
30 });
31 });
32}
33 
34// express.raw keeps the body as the exact bytes ModelRiver signed
35app.post('/tools/sales-summary', express.raw({ type: 'application/json' }), async (req, res) => {
36 if (!verifyToolCall(req.body, req.headers, SECRETS)) {
37 return res.status(401).json({ error: { message: 'Bad signature' } });
38 }
39 
40 const call = JSON.parse(req.body.toString('utf8'));
41 
42 // Who is asking comes from end_user, which your backend sent and ModelRiver signed.
43 // Never take it from call.arguments: the model wrote those.
44 const storeId = call.end_user.claims.store_id;
45 const period = call.arguments.period ?? 'this_week';
46 
47 const summary = await db.salesSummary(storeId, period);
48 if (!summary) {
49 return res.status(404).json({
50 error: { message: 'No sales data for that period', user_message: 'There are no sales for that period yet.' },
51 });
52 }
53 
54 res.json({ period, revenue: summary.revenue, orders: summary.orders, change_vs_previous: summary.change });
55});
56 
57app.listen(3000);

Python (FastAPI)

PYTHON
1import hashlib, hmac, json, os, time
2from fastapi import FastAPI, Request
3from fastapi.responses import JSONResponse
4 
5app = FastAPI()
6SECRETS = [os.environ["MODELRIVER_TOOL_SECRET"]]
7 
8def verify_tool_call(raw_body: bytes, headers, secrets, tolerance_seconds: int = 300) -> bool:
9 timestamp = headers.get("x-modelriver-timestamp", "")
10 call_id = headers.get("x-modelriver-tool-call-id", "")
11 signatures = [
12 part.strip()[3:]
13 for part in headers.get("x-modelriver-signature", "").split(",")
14 if part.strip().startswith("v2=")
15 ]
16 
17 if not timestamp.isdigit() or not call_id or not signatures:
18 return False
19 if abs(time.time() - int(timestamp)) > tolerance_seconds:
20 return False
21 
22 signed = f"v2.{timestamp}.{call_id}.".encode() + raw_body
23 for secret in secrets:
24 expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
25 if any(hmac.compare_digest(expected, given) for given in signatures):
26 return True
27 return False
28 
29@app.post("/tools/sales-summary")
30async def sales_summary(request: Request):
31 raw_body = await request.body() # the exact bytes ModelRiver signed
32 if not verify_tool_call(raw_body, request.headers, SECRETS):
33 return JSONResponse({"error": {"message": "Bad signature"}}, status_code=401)
34 
35 call = json.loads(raw_body)
36 
37 # Who is asking comes from end_user, never from the arguments.
38 store_id = call["end_user"]["claims"]["store_id"]
39 period = call["arguments"].get("period", "this_week")
40 
41 summary = await db.sales_summary(store_id, period)
42 if summary is None:
43 return JSONResponse(
44 {"error": {"message": "No sales data for that period",
45 "user_message": "There are no sales for that period yet."}},
46 status_code=404,
47 )
48 
49 return {"period": period, "revenue": summary.revenue, "orders": summary.orders,
50 "change_vs_previous": summary.change}

The endpoint must be reachable from the internet over HTTPS. For an endpoint on your own machine, see Testing a local endpoint.

3. Register the tool

On the Tools tab, select Add tool and fill in:

FieldValue
Nameget_sales_summary
Description for the modelReturns revenue, order count and the change against the previous period for the signed-in user's store. Use it for any question about how sales are going.
Progress labelReading this week's sales…
Endpoint URLhttps://api.yourapp.com/tools/sales-summary
Timeout10 (seconds)
What does calling it do?Only reads data

In Example arguments, type an example of what a call should carry:

JSON
1{
2 "period": "this_week"
3}

Select Build parameters from example. ModelRiver works out a JSON Schema from the example and lists the arguments under Parameters: every key becomes a required argument, and nothing else is allowed. Then select Edit schema and tighten it where that helps. Here period is made optional and limited to three values:

JSON
1{
2 "type": "object",
3 "properties": {
4 "period": {
5 "type": "string",
6 "enum": ["today", "this_week", "this_month"],
7 "description": "The period to summarize"
8 }
9 },
10 "additionalProperties": false
11}

Two things decide how well the model uses a tool: the description, which is all it knows about when to call it, and the schema. "additionalProperties": false matters, because a call with a field the schema doesn't list is then refused before it reaches you.

4. Send a test call

Open the tool's ⋯ menu and select Send test call. ModelRiver calls your endpoint once, signed like a real request and marked "mode": "test", and shows what it sent and what came back.

This works before you save, so you can fix the endpoint and the tool together. Organization owners and admins can send test calls.

A test call goes to the tool's public HTTPS address. While your endpoint only runs on your machine, start modelriver tools and choose My CLI to send the test call to it instead.

5. Save and publish

Save the workflow, then publish it. Like every other workflow setting, tools take effect for live traffic when the release is published.

6. Send a request

From your backend:

Bash
curl -X POST https://api.modelriver.com/v1/ai/async \
-H "Authorization: Bearer $MODELRIVER_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"workflow": "sales_chat",
"messages": [{"role": "user", "content": "How did we do this week?"}],
"end_user": {"id": "user_812", "claims": {"store_id": "st_44"}}
}'

The response is the usual async one, with channel_id and ws_token. Pass those to your frontend and connect with the Client SDK:

TSX
1import { useModelRiver } from '@modelriver/client/react';
2 
3function Assistant() {
4 const { connect, toolCalls, response, error, hasPendingRequest, cancel } = useModelRiver();
5 
6 // connect({ channelId, wsToken, websocketUrl, websocketChannel }) with what your backend returned
7 
8 return (
9 <div>
10 {toolCalls.map((call) => (
11 <p key={call.id}>{call.label ?? call.name}{call.status === 'running' ? '' : ' ✓'}</p>
12 ))}
13 {hasPendingRequest && <button onClick={() => cancel()}>Stop</button>}
14 {response?.status === 'success' && <pre>{JSON.stringify(response.data, null, 2)}</pre>}
15 {error && <p>{error}</p>}
16 </div>
17 );
18}

While the request runs, toolCalls shows "Reading this week's sales…". The final response carries the answer and what the request used: meta.tool_loop is { "rounds": 2, "tool_calls": 1 }, which is two requests on your plan.

7. Look at the request

Open Request Logs and select the request. The Timeline shows each model round and, under it, each tool call with its duration and HTTP status. If the project saves full request and response text, each call also shows its arguments and result.

Next steps