Many Tools and Large Results
Three features keep an agent’s context small when its tools return a lot of data or when it has many tools:
- Large results. A tool result too large for the context is stored whole. The model gets its shape, a preview and a reference, and reads the parts it needs with
query_tool_result. - Tool search. An agent with many tool actions sends the model only the core ones. The model finds the rest with
search_tools. - Tool scripts. The model writes a short Python script that calls read-only tool actions as functions and loops, filters or aggregates over their results. Only the script’s final value comes back to the context. The tool is
run_tool_script.
All three are on by default and work with every LLM provider that supports tool calling, because they are ordinary tools. They add nothing to a turn that doesn’t need them.
Large tool results
TOOL_RESULT_MAX_TOKENS (20,000 by default) caps how much of one tool result enters the model’s context. The cap does not change what is recorded: the conversation keeps its usual short preview of each call’s result, and the tool-call journal keeps the result up to 400,000 characters.
When a result is over the cap, DocsGPT stores it whole and gives the model this in its place:
The result of list_issues is too large for the context (48,210 tokens; the limit is 20,000), so it was stored whole as ref res-20261204-3f9a1c2b7d4e.
Shape: JSON array of 1,240 items; first item is an object with keys: id (integer), title (string), state (string), labels (array[3]), created_at (string)
Preview:
[{"id": 1812, "title": "...", ...},
...]
(first 14 of 1,240 items)
Read it with query_tool_result(ref="res-20261204-3f9a1c2b7d4e", expression=...) using a JMESPath expression, ...The preview is about TOOL_RESULT_PREVIEW_TOKENS (1,500) long. A result that is a JSON object or array, or text that parses as one, is stored as JSON; anything else is stored as text. An MCP result is stored as its data, not as its content blocks: its text when that parses as JSON, else the tool’s structured content, else its text (several text blocks as a list). Secret values the tool’s owner exposed to the model are redacted before the result is stored.
The result is cut to its start and end instead, as before this feature, when:
TOOL_RESULT_REFS_ENABLEDisfalse,- the result is larger than
TOOL_RESULT_REF_MAX_BYTES(8 MB), - storing it fails,
- it comes from the last tool round of the turn, after which the model can’t call another tool, or
- another tool of the turn already has an action named
query_tool_result.
A page of query_tool_result itself is never stored again.
A background job’s result longer than AUTO_RESUME_MAX_RESULT_CHARS is stored the same way when the job finishes, for the job’s conversation, after the tool-result guardrails pass it whole. The resumed turn, check_job and the user’s next message get its ref, shape and preview instead of the cut text, and query_tool_result reads it.
query_tool_result
The model gets query_tool_result in the turn that stores a result, and in later turns of a conversation that holds one. It takes:
| Argument | Description |
|---|---|
ref | The stored result’s ref, such as res-20261204-3f9a1c2b7d4e. Required. |
expression | A JMESPath expression over a JSON result. Without it the query reads the whole result, a page at a time. Text results take no expression. |
pattern | A case-insensitive regular expression that keeps only matching items of a JSON list, or matching lines of a text result. |
offset | Items or lines to skip; 0 by default. |
limit | Most items or lines to return, up to 1,000. A text result returns 200 lines when it is not set. |
JMESPath can count, filter, sort, project and slice:
| Expression | Returns |
|---|---|
length(@) | How many items the list has |
[?state=='open'].id | The ids of the open items |
sort_by(@, &price)[-5:] | The five most expensive items |
max_by(@, &stars).name | The name of the item with the most stars |
data[0:20].{id: id, name: name} | Two fields of the first 20 items under data |
A JSON query that selects a list returns a page of it, with total, offset, count, items and next_offset while more remain. A text query returns numbered lines and the offset to continue from; a line over 2,000 characters comes in parts, and offset and limit count each part. Each page is at most 8,000 tokens (and under TOOL_RESULT_MAX_TOKENS). An expression that fails returns the error and the result’s shape so the model can try again. A pattern is limited to 200 characters and 2 seconds of matching.
Where results are stored
Results are files in the storage backend (STORAGE_TYPE), under tool_results/: in the data home on local storage, in the bucket on S3. They are not artifacts and don’t appear in anyone’s artifact list.
A result belongs to the user whose turn stored it and to its scope: the conversation, or for a run without one (a workflow run, a scheduled or webhook run) that run. Only the same user in the same scope can read it. In a shared conversation, one participant can’t read a result another participant’s turn stored.
A turn that is not saved to a conversation and belongs to no run, such as a stateless /v1/chat/completions call or a request with persist: false, keeps its results in memory for that turn only, up to 8 MB in all. Past that, results are cut.
A daily task deletes stored results older than TOOL_RESULT_REF_RETENTION_DAYS (30). It runs on the Celery beat scheduler, so beat must run somewhere (see Development Environment). After that, a query for an expired ref tells the model to call the tool again. Each run checks the 90 days past the retention window. If you lower the retention by more than 90 days, or beat was down for longer than that, delete the older tool_results/<YYYYMMDD> folders in storage yourself.
Tool search
An agent with dozens of MCP or API tool actions would otherwise send every action’s schema with every model call. With tool search, past a threshold the model gets only the core actions and a search_tools tool.
Tool search starts when the agent’s own actions in a turn are more than TOOL_SEARCH_THRESHOLD (30). DocsGPT’s own server tools don’t count toward the threshold. It does nothing for a model without tool support.
These stay listed every turn:
- DocsGPT’s server tools: retrieval (
internal,graph_search,wiki),think,ask_user, attachments,view_image,check_job,report_cannot_complete, andquery_tool_resultandrun_tool_scriptonce the turn has them - client-side tools (tools the API caller runs)
- actions called earlier in the conversation, by the model or from a script, so a multi-turn chat doesn’t search again
- actions called earlier in the same turn, including a turn resumed after an approval
- actions the agent’s prompt names (see below)
The search_tools description names the tools it reaches and how many actions each has, for example GitHub (41), Notion (12). When the turn can get tool scripts, it also says that read-only matches can be called together from one script. The model calls it with a few words or an exact name:
search_tools(query="create issue", limit=5)Ranking runs in the API process, with no embeddings and no network call. It weighs words in the action’s name most, then the tool’s name, the parameter names, and the descriptions. An exact action name ranks first. The result lists each match with its tool, description, parameters and, when known, what it returns. The matches become callable at once and stay listed for the rest of the turn. limit is 5 by default and at most 10.
A call to a held-back action by its exact name runs without a search, and the action stays listed for the rest of the turn. It goes through the usual permission and approval checks.
Naming actions in the prompt
To keep an action listed without a search, name it in the agent’s prompt. A name with more than one word, such as list_issues or getPage, counts wherever it appears. A one-word name, such as search, counts only in backticks (`search`) or written as a call (search(). The agent’s own prompt template is read, not the documents or values filled into it. A system prompt sent by an API caller in place of the agent’s is not read.
Tool scripts
Some tasks need many tool calls whose results matter only in aggregate: fetch every open issue and count them by label, look up each order’s customer and total by region. Called one by one, every result passes through the model’s context. With run_tool_script the model writes the loop once:
orders = await list_orders(status="open")
totals = {}
for order in orders:
customer = await get_customer(customer_id=order["customer_id"])
totals[customer["region"]] = totals.get(customer["region"], 0) + order["amount"]
sorted(totals.items(), key=lambda item: item[1], reverse=True)[:5]Only the last expression, five pairs, comes back to the model. print() output comes back too, and with both the result is {"result": ..., "printed": ...}. A large script result goes through the same cap as any tool result, so it may become a stored result.
The tool’s description lists the callable actions as Python stubs, typed from their parameters and, when known, what they return:
class ListOrdersItem(TypedDict):
id: str
customer_id: str
amount: float
async def list_orders(status: Literal["open", "closed"] | None = None) -> list[ListOrdersItem]:
"""List orders, newest first."""When the stubs would be long, the description shows signatures only, then names only. A return type is Any when the tool doesn’t say what it returns.
What a script can call
A script can call only actions that read and don’t need approval:
- built-in and custom Python tool actions their code declares read-only, in
action_contractsor with"access": "read"in the tool’s own metadata (see Creating a Custom Tool), - MCP actions the server marks
readOnlyHintwith nodestructiveHintand no write verb in their name (see MCP Tools), and every action of a built-in connector’s read-only endpoint, such as GitHub’s (a connection made before this release gets that last rule once you refresh it), - API tool actions that use
GET,HEADorOPTIONS(see API Tool).
An action set to Needs approval is left out, and so are client-side tools, ask_user, the remote device, the code executor, the artifact tool, check_job, view_image, think, monitor_list, the attachments reader and the meta-tools on this page. Actions held back by tool search can be called from a script by name: the description shows stubs only for the listed ones.
Scripts run their calls without a person watching each one, so the read-only rule is what keeps them safe. Each call still goes through the same checks as a direct call. If a call would pause for approval, need a connection, or be refused (an API-key caller can’t make changes as the owner, for example), the script gets a PermissionError that tells the model to call that tool directly, where the approval card can be shown.
A call returns the tool’s value as plain JSON data: an MCP tool’s structured content, an API action’s response body, or a built-in tool’s result (parsed when it is JSON text and the tool says it returns an object or a list). A script that calls a name it can’t, such as an action that writes, is rejected by the type check before it runs. A call that fails, or is refused when it runs, raises an exception the script can catch. Calls run one at a time in the order the script makes them; asyncio.gather works but does not run them in parallel. Script calls always run in the foreground and are never handed off to a background job.
The tool is offered when tool scripts are on, the Monty sandbox is installed (it is a core dependency), the turn has at least TOOL_SCRIPT_MIN_ACTIONS (3) actions a script can call, and at least one of them is listed for the model. In an agentless chat, the default chat tools (DEFAULT_CHAT_TOOLS) don’t count toward either condition, though a script can call them.
The actions counted toward TOOL_SCRIPT_MIN_ACTIONS include those held back by tool search. When tool search holds back every one of them, the turn starts without run_tool_script, so it doesn’t pay for the tool’s description in every model call. Once a search, or a call by name, lists one of them, run_tool_script is added for the rest of the turn; a search that adds it says so in its result. A call to run_tool_script by name adds it too, and a conversation that ran a script earlier gets it from the start of each later turn. A turn resumed after an approval keeps it.
The sandbox
Scripts run in Monty, a Python interpreter written in Rust, in a separate worker process. A script has no file system, network or environment variable access and can’t import arbitrary modules. Part of the standard library is available: json, re, math, statistics, collections, datetime, itertools and functools, among others. time.sleep returns at once. Credentials never enter the sandbox: the tool runs in DocsGPT, and only JSON-like values cross in either direction.
Each script is type-checked before it runs. A syntax error, a type error, a runtime error or a limit returns the error with its traceback, the tool calls the script made and how each ended, so the model can fix the script and run it again.
| Limit | Default |
|---|---|
| Tool calls per script | 50 (TOOL_SCRIPT_MAX_CALLS) |
| Tool calls by all scripts in one turn | 200 (TOOL_SCRIPT_MAX_CALLS_PER_TURN) |
| Computing time, not counting tool calls | 30 seconds (TOOL_SCRIPT_TIMEOUT_SECONDS) |
| Memory, tool results the script holds included | 128 MB (TOOL_SCRIPT_MAX_MEMORY_MB) |
| Script length | 20,000 characters |
| Printed output | 1 MB |
| One call’s arguments | 128 KB as JSON |
| The script’s result | TOOL_RESULT_REF_MAX_BYTES (8 MB) as JSON |
Each call is run, checked and journaled like a direct call, so a billed tool (Brave Search, for example) is billed per call.
In the chat and the journal
The chat shows one step for the script, with its code and its result. The calls it made are not shown as separate steps and are not saved with the conversation. Each one is written to the tool-call journal (tool_call_attempts) with a call id of the form <script call id>:script:<run>:<n>, which links it to the script’s call. A call refused inside a script is journaled as refused.
Settings
Set these in .env. The Settings Reference describes each one.
| Setting | Default | Controls |
|---|---|---|
TOOL_RESULT_MAX_TOKENS | 20000 | Largest tool result that enters the context whole; 0 turns the cap off |
TOOL_RESULT_REFS_ENABLED | true | Store results over the cap; false cuts them |
TOOL_RESULT_PREVIEW_TOKENS | 1500 | Length of the preview the model gets with a ref |
TOOL_RESULT_REF_MAX_BYTES | 8000000 | Largest result stored; also the largest value a script may return |
TOOL_RESULT_REF_RETENTION_DAYS | 30 | Days a stored result stays readable |
TOOL_SEARCH_ENABLED | true | Tool search for agents past the threshold |
TOOL_SEARCH_THRESHOLD | 30 | An agent’s own actions before the rest wait for search_tools |
TOOL_SCRIPT_ENABLED | true | Offer run_tool_script |
TOOL_SCRIPT_MIN_ACTIONS | 3 | Actions a script can call, listed or held back, before the tool is offered |
TOOL_SCRIPT_MAX_CALLS | 50 | Tool calls per script |
TOOL_SCRIPT_MAX_CALLS_PER_TURN | 200 | Tool calls by all of a turn’s scripts |
TOOL_SCRIPT_TIMEOUT_SECONDS | 30 | Computing seconds per script, tool calls not counted |
TOOL_SCRIPT_MAX_MEMORY_MB | 128 | Memory per script |
Per-agent overrides
An agent’s config can turn tool search and tool scripts on or off for that agent, and set its own search threshold. A key that is not set keeps the instance setting.
{
"tool_search": { "enabled": true, "threshold": 15 },
"tool_script": { "enabled": false }
}threshold is from 1 to 1000. The agent builder has no control for these keys yet. Set them through the API or an agent file:
- API. Send the agent’s whole
configwith the keys added toPUT /api/update_agent/<agent_id>. The update replaces the storedconfig, so start from the agent’s current one (GET /api/get_agent?id=<agent_id>). The agent builder keeps keys it doesn’t show when it saves. - Export and import. Export the agent, add the keys under
spec.configin the YAML file, and import it back.
Last updated on
⏳ Background Jobs
How DocsGPT hands slow tool calls off to background jobs, resumes the conversation with their results, notifies the user (toasts, unread marks, Web Push), and how check_job and watch work.
📡 Monitors and Links
How the monitor tool watches a web page or any tool, wakes the conversation on ingests, webhook trigger links and human approval links, how link secrets reach a sender through secret references, and how its checks, limits and safety rules work.