Hosted tools (opt-in)
Rendered from docs/hosted-tools.md at commit 813abb1662f7. The repository file is authoritative.
By default ModelSaar executes no tools: a model's tool call is returned to the caller, who runs it. With
hosted_tools.enabled the gateway can run a catalogue the operator declared on POST /v1/responses
and loop until the model answers:
model turn ──► hosted call(s) the model asked for ──► model turn ──► … ──► answer
(catalogue only, this key only, (or: a call the caller must run,
bounded, recorded) or an explicit `incomplete`)
Three kinds of tool exist. Nothing else does.
| kind | what it is | what it can reach |
|---|---|---|
file_search |
similarity search over UTF-8 text the administrator registered, embedded through an existing embeddings[] alias |
the gateway's own state database and the embedding alias; nothing is fetched |
http |
one fixed method (GET or POST) and URL template with declared scalar parameters |
the template's host, which must be on hosted_tools.allowed_hosts; redirects are never followed |
mcp |
tools of an MCP server (Streamable HTTP transport, MCP 2025-06-18), restricted to an allowlist of tool names | a loopback address (127.0.0.0/8, ::1, localhost) on allowed_hosts; no stdio servers — the gateway starts no processes |
Not offered, by design: a code interpreter, a shell or command runner, computer use, image generation,
open web search or browsing (a search exists only as an http tool that points at an endpoint you run),
and any way for a request to supply a URL, a host, a header, a method or a command.
Configuration
embeddings:
- alias: text-embed
deployments: [ollama/embeddinggemma-2:latest]
hosted_tools:
enabled: true # default false: every hosted tool type is refused, as in 0.2.0
# Hard limits on one response
max_steps: 4 # model turns
max_calls: 8 # hosted tool calls
deadline_s: 120 # one wall clock for the whole response (see "The deadline")
max_result_bytes: 16384 # one tool result as handed to the model (UTF-8)
max_total_result_bytes: 65536
audit_max_rows: 10000
# Where http and mcp tools may connect (host or host:port). Every tool URL must be on it.
allowed_hosts: ["api.internal.example:8443", "127.0.0.1:8931"]
# Who may use what. Nobody by default.
default_tools: [] # catalogue names any authenticated key may use
access:
- caller: "9f2c…64 hex…" # the key's full SHA-256 — `modelsaar tools callers` prints it
tools: [handbook, weather, notes]
file_search:
- name: handbook
description: "The team handbook."
embedding_alias: text-embed # must be an embeddings[] alias that accepts text
max_results: 5
chunk_chars: 1200
chunk_overlap: 150
max_documents: 200
max_document_bytes: 1048576
max_chunks: 5000
http:
- name: weather
description: "Current weather for a city."
method: GET # GET or POST; fixed
url: "https://api.internal.example:8443/v1/weather/{city}?units={units}"
parameters: # the JSON-schema subset below
type: object
properties:
city: {type: string, maxLength: 64, description: "City name"}
units: {type: string, enum: [metric, imperial]}
required: [city]
header_env: {Authorization: WEATHER_API_AUTH} # header value read from this environment variable
timeout_s: 10
max_response_bytes: 16384
mcp:
- name: notes # the `server_label` on the wire
url: "http://127.0.0.1:8931/mcp"
tools: [search_notes, get_note] # required: the MCP tool names this server may be asked for
header_env: {}
timeout_s: 15
max_response_bytes: 16384
Rules the loader enforces (a violation is a configuration error, not a runtime surprise):
- Tool names are unique across the three kinds;
file_searchis reserved. - An
httpormcpURL must behttp(s)://host[:port]/…without credentials or fragment, onallowed_hosts. AnmcpURL must be a loopback address. httpURL placeholders ({name}) may appear in the path and in query values only — never in the scheme, host, port or a query name. Every placeholder is a declared parameter; a path placeholder is a required one.parametersis a flat object of scalars:string,integer,number,boolean, each with optionaldescription,enum,maxLength(strings default to 256),minimum,maximum. No nested objects or arrays;additionalPropertiesis always false.header_envnames environment variables; a header value never appears in the configuration.Host,Content-Type,Acceptand the MCP protocol headers cannot be set.access[].calleris the full SHA-256 of an API key (64 lower-case hex characters; the 12-character caller id is refused), and every name inaccess/default_toolsis in the catalogue.file_search[].embedding_aliasis anembeddings[]alias whose contract accepts text.
Who may use a tool
A key is identified for authorization by the full SHA-256 of the key (64 hex characters), so no key
appears in the configuration. modelsaar tools callers prints it for each key in the key file, without
printing a key:
$ modelsaar tools callers
API key #1: caller 9f2c41d0…(64 hex)…77ab (audit id 9f2c41d0a1b2) tools: handbook, notes, weather
API key #2: caller 03be9a55…(64 hex)…c410 (audit id 03be9a55d6e7) tools: (none)
The 12-character audit id is the caller id that decision records and the audit show. It is a display
prefix of the digest and authorizes nothing: an access entry must carry the whole digest, the
comparison is over the whole digest, and a prefix in the configuration is a load error.
Tool connections discard cookies from responses and request uncompressed data. A server must return identity encoding. These rules keep the byte limit meaningful before decoding.
A key can use a tool only when default_tools or its own access entry names it. A tool that is not in
the catalogue and a tool the key may not use are refused with the same 400 hosted_tool_unavailable,
so a key cannot find out what exists. The admin key gets no tools by being the admin key.
Registering documents
file_search searches text the administrator registered. The text travels in the request; the gateway
opens no path on its host and fetches nothing.
modelsaar tools add-document handbook ./handbook.md # the CLI reads the file and sends its text
modelsaar tools documents handbook
modelsaar tools remove-document handbook file_3f9c…
(POST /admin/hosted-tools/documents {"store", "filename", "text"}, GET …?store=, DELETE {"store",
"file_id"}; admin key.) The request is bounded by the server-wide server.max_request_bytes like any
other request, and the document by the set's max_document_bytes. Plain UTF-8 text and Markdown only —
PDF, Office and HTML are not parsed.
Registering a filename again replaces it. The text is cut into chunks of chunk_chars characters
(preferring paragraph and sentence breaks), each chunk is embedded through embedding_alias — an ordinary,
recorded embeddings request — and stored with its vector in the state database.
An index belongs to the embedding space it was built in. If the alias is later answered from another model
or width, searching fails with index_stale and registration is refused with 409 until the set's
documents are removed and registered again; vectors from two spaces are never compared.
Wire format
Hosted tools are requested on POST /v1/responses next to ordinary function tools:
{
"model": "auto",
"input": "What does the handbook say about expenses, and what is the weather in Oslo?",
"tools": [
{"type": "file_search", "vector_store_ids": ["handbook"], "max_num_results": 3},
{"type": "modelsaar_http", "name": "weather"},
{"type": "mcp", "server_label": "notes", "allowed_tools": ["search_notes"], "require_approval": "never"},
{"type": "function", "name": "lookup_order", "parameters": {"type": "object", "properties": {"id": {"type": "string"}}}}
],
"max_tool_calls": 4
}
| tool | fields | notes |
|---|---|---|
file_search |
vector_store_ids (1–4 catalogue names), max_num_results (≤ the catalogue's max_results) |
filters and ranking_options are refused, not ignored |
modelsaar_http |
name (a catalogue name) — nothing else |
a gateway-specific type: OpenAI's API has no equivalent. A url, method or headers in the request is a 400 |
mcp |
server_label (a catalogue name), optional allowed_tools (a subset of the catalogue's list), require_approval: "never" (required) |
server_url, headers, connector_id are refused: the address is the operator's. There is no approval round trip, so the request must say never explicitly rather than have "always" silently ignored |
function |
as before | caller-executed; never run by the gateway |
Other request fields: max_tool_calls lowers the per-response call limit (it cannot raise it).
tool_choice accepts the usual values and {"type": "file_search"}, {"type": "modelsaar_http", "name"},
{"type": "mcp", "server_label", "name"}; it applies to the first model turn only — later turns are
free to answer. store, previous_response_id and conversation work as documented in
protocols.md.
Every other tool type (web_search, code_interpreter, computer_use_preview, image_generation,
shell, …) is 400 unsupported_responses_feature whether or not hosted tools are enabled.
What the model sees
Each hosted tool is presented to the model as an ordinary function, through the same chat path as any other request (so the deployment needs tool-calling support, as for caller-executed tools):
| tool | function name | parameters |
|---|---|---|
file_search |
file_search |
{query: string} |
modelsaar_http |
the catalogue name | the catalogue's parameters |
mcp |
<server_label>__<tool> |
the server's inputSchema for that tool (bounded to 8 KiB; larger → not offered) |
For MCP the tool description and schema are the server's text (description bounded to 1024
characters). Only allow-listed tools are shown; a server's instructions and its other tools never reach
the model.
MCP sessions are per key. The upstream session (Mcp-Session-Id), the negotiated protocol version and
the cached tool listing are kept per (full key identity, catalogue server). Two keys that may both use
one server each get their own session with it; one key's session ending, or anything a server ties to a
session, never carries over to another key.
Output items
Each hosted call is one item in output, in order, carrying the call and its result:
{"id": "fs_…", "type": "file_search_call", "status": "completed", "call_id": "call_1", "error": null,
"queries": ["expense report deadline"],
"results": [{"file_id": "file_…", "filename": "handbook.md", "score": 0.83, "text": "Expense reports are due …"}]}
{"id": "http_…", "type": "modelsaar_http_call", "status": "completed", "call_id": "call_2", "error": null,
"name": "weather", "arguments": "{\"city\": \"Oslo\"}", "output": "{\"temp_c\": 4}"}
{"id": "mcp_…", "type": "mcp_call", "status": "failed", "call_id": "call_3",
"server_label": "notes", "name": "search_notes", "arguments": "{\"query\": \"x\"}", "output": null,
"error": {"code": "tool_error", "message": "the notes database is offline"}}
status is completed or failed. call_id is the model's tool-call id; results are always included
(there is no include switch). The response object also carries a trace:
"modelsaar": {"hosted_tools": {"steps": 2, "calls": 1, "request_ids": ["…", "…"], "deployments": ["ollama/qwen3.8:latest", "ollama/qwen3.8:latest"]}}
and the headers X-ModelSaar-Hosted-Steps / X-ModelSaar-Hosted-Calls. Each model turn is an ordinary
routed request with its own decision record (modelsaar decisions, GET /admin/decisions/{request_id});
the turns of one response share an affinity session, so they prefer one deployment while every hard filter
still applies.
How a response ends
| situation | result |
|---|---|
| the model answers | status: "completed"; hosted items, then the message |
the model calls a caller-executed function tool (alone or next to hosted calls) |
completed; the hosted calls of that turn are run and returned as items, the caller's call is returned as a function_call item. The caller runs it and continues |
| a hosted tool fails (timeout, HTTP error, redirect, bad arguments, result too large, MCP error, …) | the item is failed with error {code, message}; the model is given {"error": …} as the tool result and the loop continues within its limits |
| the model still asks for tools on its last allowed turn | status: "incomplete", incomplete_details: {"reason": "max_tool_steps"}; those calls are not run (no turn is left to read them) |
more calls than max_calls / max_tool_calls |
incomplete, max_tool_calls; calls already run are in output |
| the deadline passes | incomplete, tool_deadline, returned at the deadline; whatever was in flight is cut and nothing further starts (see "The deadline") |
results exceed max_total_result_bytes |
incomplete, tool_output_bytes |
| a model turn fails after tools ran | the turn's error status, with error.modelsaar.hosted_tools listing what did run (it may have had effects) |
Error codes on a failed item: invalid_arguments, timeout, unreachable, http_status,
redirect_refused, unsupported_content_type, response_too_large, result_too_large,
tool_misconfigured, mcp_error, tool_error, index_stale, embedding_failed, deadline.
A result that is too large is refused whole — it is never truncated and passed on as if complete.
file_search returns fewer whole passages rather than a cut one.
Continuing
- Stateless: send the previous
outputitems back ininput(the usualinput += response.output), hosted items included. A hosted item is replayed as the call and the tool result the model saw; it does not run the tool again. previous_response_id(store: true) andconversation: the hosted items are stored with the turn and replayed the same way. In a conversation the stored items keep the ids the response carried; the turn is committed whole or not at all, and the conversation's turn lock is held (and renewed) for the whole loop — a second writer gets409 conversation_locked. A caller cannot add a hosted item of its own to a conversation (neither with the items route nor asinputof a turn).
Streaming
With stream: true the loop is reported per step, not per token: response.created, then for each
hosted call response.output_item.added → response.<type>.in_progress →
response.<type>.completed | .failed → response.output_item.done, then each model turn's items (a
turn's text arrives as one response.output_text.delta when that turn is complete), then
response.completed, response.incomplete or response.failed. The first model turn decides the
HTTP status as for any request — a refusal there (no eligible deployment, admission, an upstream failure)
is an ordinary error response, so the stream's headers arrive when that turn is complete; a failure in a
later turn is response.failed. A response that could not be stored ends as response.failed, never as
completed. If the caller disconnects, the loop stops; a model turn
cut in flight keeps an uncertain slot hold, and nothing is stored.
Safety properties
| property | how it is enforced |
|---|---|
| no arbitrary destination | the scheme, host and port of an http call are the template's. Argument values are validated against the declared schema, then percent-encoded into a single path segment (. and .. are refused) or sent as query values / JSON body fields. The built URL is checked against the template's host again before it is used |
| no redirects | the HTTP client never follows one; a 3xx is a failed call (redirect_refused) — for http tools and for MCP endpoints |
| a direct connection | proxy variables in the gateway's environment (HTTP_PROXY, HTTPS_PROXY, …) are ignored for tool calls, so "loopback" and "this allow-listed host" mean a connection there and not a hop through something else. A tool behind a proxy needs an endpoint the gateway can reach directly |
| no off-list network access | every tool URL must be on allowed_hosts at load; a request cannot supply addresses; MCP is loopback only |
| no code or command execution | there is no tool kind that runs anything; MCP stdio (which starts a process) is not implemented |
| tool text is data | a tool's output goes to the model as a tool message and into the response item. The gateway never parses it for addresses, commands or instructions and takes no action because of it. An MCP server's requests to the client (sampling, elicitation) are not answered: the gateway declares no client capabilities |
| credentials stay where they are | header_env values are read from the environment at call time, sent only to that tool's endpoint, and appear in no response, audit row, decision record, status page or log. The caller's API key is never sent to a tool |
| per-key authorization | checked for every request before any model or tool is contacted |
| bounds | steps, calls, wall clock, per-result and total bytes, per-tool timeout and response cap, argument size (16 KiB) |
What this does not protect against: a model that is talked into misusing a tool it is allowed to
use. Text returned by a tool (or written in a registered document, or in an MCP tool's description) can
try to steer the model, and the gateway cannot tell persuasion from content. The limits above are what
contain it: the model can only call this key's tools, with schema-valid arguments, a bounded number of
times. So give a key only the tools it needs, treat a POST tool as "the model may do this on its own",
and keep MCP allowlists short. modelsaar doctor lists POST tools, default_tools and unset credentials.
The deadline
deadline_s is one absolute wall clock per response. It starts when the request has been read and
authenticated — before an MCP server is asked what it offers — and everything runs against what is left of
it: catalogue planning, routing, the wait for admission, every model turn (the first one included), the
query embedding of a file_search, and every HTTP and MCP call.
| when it passes | what happens |
|---|---|
| while an MCP server is being asked for its tools (before any model turn) | 502 hosted_tool_unreachable at the deadline, not after the tool's own timeout |
| before a model turn or tool call starts, or while a turn waits for admission | nothing is dispatched; the response is incomplete / tool_deadline |
| while a model turn is being answered | the turn is cut. The backend may still be generating, so its slot becomes an uncertain hold that frees after admission.uncertain_hold_s; the turn is not retried on another deployment and the circuit breaker is not charged. The response is incomplete with the items that had finished, and modelsaar.hosted_tools.deadline says which turn was cut |
| while a tool is running | the call is cut: a failed item with timeout (a file_search whose embedding was in flight keeps an uncertain slot the same way); then incomplete |
After the deadline nothing further is dispatched for that response — no tool call, no model turn, no
failover. The caller gets the incomplete response at the deadline, not when a slow backend finishes.
The decision record of a cut turn has outcome deadline.
Audit
Every hosted call is recorded in the state database (hosted_tools.audit_max_rows, oldest dropped):
time, the caller's 12-character audit id (never the full digest), response id, the request id of the model turn that asked, step, item id, tool, kind,
target (HTTP method or MCP tool), duration, argument bytes, result bytes, outcome and error code.
Arguments and results are stored only when security.log_prompts is on. The audit is admin-only:
modelsaar tools calls --limit 20
GET /admin/hosted-tools?calls=20
GET /admin/hosted-tools?response_id=resp_…
GET /admin/hosted-tools / modelsaar tools status show the catalogue (hosts, parameter names, header
names), who may use what, document counts and what each MCP server currently offers.
Content at rest that hosted tools add: registered documents and their vectors (until removed); tool results inside stored responses and conversations (their TTLs apply); audit rows (metadata; content only with prompt logging).
What is and is not verified
Fixture evidence, tests/test_hosted_tools.py (34 cases): a scripted fixture model drives real loops through the
gateway against real loopback servers — an HTTP API and an MCP server over Streamable HTTP (JSON and SSE
answers) — and a document index embedded through the fixture embedding model. Covered: each tool kind end
to end; per-key authorization and the indistinguishable refusal; refused request fields and tool kinds;
destination and path encoding; redirects; credentials and redaction; tool text as data; step, call, time
and byte limits; failed tools; a failing model turn after a tool ran; caller-executed tools in the same
turn and stateless replay; stored responses; conversations and their lock; streaming, including a caller
that disconnects; the audit with and without prompt logging; MCP session expiry, protocol mismatch,
redirecting and unreachable servers; a stale index; the CLI; authorization by the whole key digest (a
matching 12-character prefix grants nothing); separate MCP sessions for two keys on one server; the single
deadline across planning, admission, the first and a later model turn, and embedding; the admin request
bound.
A hardware run exercised all three tool types with Qwen2.5-0.5B-Instruct, real document embeddings, and the official Python MCP SDK using both JSON and SSE. The official OpenAI Python client also read a streamed file search. Every final answer contained the fresh value returned by the corresponding tool. The two-document trial measures interoperability. Retrieval quality across a corpus and how accurately another model chooses tools require evaluation on that workload.
Document search uses character-based chunks and a linear scan bounded by max_chunks.