Skip to content

feat(core): deferred tools loaded through a search tool - #110

Merged
gopaljigaur merged 3 commits into
mainfrom
feat/deferred-tools
Oct 15, 2026
Merged

gopaljigaur merged 3 commits into
mainfrom
feat/deferred-tools

Conversation

@gopaljigaur

@gopaljigaur gopaljigaur commented Oct 15, 2026 •

Copy link
Copy Markdown
Owner

Every tool schema is sent with every completion. This lets a tool opt out until the model asks for it.

What changed

  • defer_loading: bool = False on BaseTool, Tool and @tool, the name Anthropic's and OpenAI's tool definitions and Pydantic AI use. MCPClient.attach(..., defer_loading=True) (and MCPBridge.attach) defers every tool of a server, including tools it lists later.
  • New module cyclops/core/tool_search.py: _ToolSearch holds one run's tools. With any tool deferred it adds a search_tools(query) tool (read only) and sends only the tools not deferred plus the search tool. A search ranks deferred tools by how many query words appear in their name and description (names split at underscores), returns up to ten (tools not loaded yet first), and adds them for the rest of the run.
  • _RunLoop._steps builds the completion kwargs and system prompt when the run starts and again only after a search added tools; other steps reuse them. In naive mode the found tools join the tools listed in the system prompt.
  • Agent raises ValueError if a tool is named search_tools while any tool is deferred.
  • Docs: a Deferred tools section in the tools guide (docs and website), the MCP guide, and the API reference signatures.

Decisions

  • Opt-in per tool, no context-window threshold. Anthropic (defer_loading), OpenAI (defer_loading) and Pydantic AI (defer_loading=True plus a search_tools fallback) all mark tools individually; none switches on by token count. A threshold would need token_counter over the schemas and get_model_info for every deployment behind a router, and would change what the model sees as tools are added, without the caller choosing it. Tools not marked are the always-loaded ones.
  • Found tools live in the run's _ToolSearch, created in _steps, so a new run (or the naive fallback's retry) starts again from the tools always sent. Nothing is stored on the agent or the session.
  • Client-side search for every provider in this PR. LiteLLM 1.105.1 maps defer_loading and tool_search_tool_regex_20251119 / bm25 for Anthropic, but its chat completion response drops the tool_search_tool_result block and returns the server_tool_use as an ordinary tool call. Checked against LiteLLM's real request builder with a mocked HTTP reply: the next request sends that call back as a client tool_use that the caller must answer, so a run could not continue. Anthropic also documents a client-side path: deferred tools stay in tools with defer_loading: true and a custom search tool returns tool_reference blocks, which keeps the prompt prefix and its cache stable. That path, the server-side one and session-wide found tools are tracked in feat(core): keep the cached prefix fixed when deferred tools are found #113.
  • Search is stdlib word overlap, like Pydantic AI's local keywords fallback (its default is the provider's native search on Anthropic and OpenAI, and the keyword search elsewhere), including its limit of 10 results and ranking tools not found yet first. The words of each deferred tool are computed once per run.

Tests

tests/test_tool_search.py: what is sent with and without deferred tools, a search adding tools for later steps and the run only (not the next run in a session), always-loaded tools, naive mode, ranking and the ten result limit, two searches in one step, search_tools under ToolPermissions, the reserved name, MCP tools deferred through MCPClient and MCPBridge against the demo server, and found tools reaching Anthropic through LiteLLM's real request builder.

uv run pytest (470 passed, 1 xfailed), uv run pre-commit run --all-files and uv run mypy cyclops pass.

Closes #74

@gopaljigaur gopaljigaur left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed 88c485d. The design matches the brief and the efficiency claims hold: kwargs and the system prompt are rebuilt only after a search adds tools, the word index is built once per run, and found tools live only in the run's _ToolSearch. defer_loading is the name Anthropic, OpenAI and Pydantic AI use, and search_tools is Pydantic AI's local tool name. Returning names and descriptions with schemas on the next step matches Pydantic AI, which returns names only. Pydantic AI's default strategy is native search on Anthropic and OpenAI and its keyword overlap elsewhere (max_results=10, a queries: list[str] argument), so "as Pydantic AI's default keywords strategy" is accurate for its local fallback only.

Findings:

  1. Prompt caching misses on tools, system prompt and full history after each search that adds tools, and again at the start of the next run in a session. Not documented.
  2. The docs say no Anthropic path exists, but Anthropic's client-side tool_reference path passes through LiteLLM 1.105.1 and would keep the prefix fixed. The server-side drop is real (reproduced) and fixed in BerriAI/litellm#46440, merged today, not yet released.
  3. Found tools reset each run, where Anthropic, OpenAI and Pydantic AI keep discoveries for the conversation.
  4. Already-found tools can take all five result slots from tools not yet found.
  5. ToolPermissions with a deny default blocks search_tools, so no deferred tool can load; undocumented.
  6. An unwrapped 110 character docstring line in MCPClient.attach.
  7. Import order nit in agent.py.
  8. Test gaps: parallel searches, re-finding a loaded tool, permissions.

Checked and fine: naive mode lists found tools with their parameters; a search with no hits returns a message and adds nothing; two searches in one step each add their tools once; a deferred tool is denied by ToolPermissions like any other; subagents get their own _ToolSearch per run; the skills tool is never deferred. uv run pytest (485 passed, 1 xfailed), pre-commit and mypy cyclops pass locally, CI is green, and the confidentiality and dash checks are clean.

Comment thread cyclops/core/run.py Resolved
Comment thread docs/guide/tools.md Resolved
Comment thread cyclops/core/run.py Resolved
Comment thread cyclops/core/tool_search.py Resolved
Comment thread docs/guide/tools.md Resolved
Comment thread cyclops/mcp/client.py Resolved
Comment thread cyclops/core/agent.py Resolved
Comment thread tests/test_tool_search.py Resolved

@gopaljigaur gopaljigaur left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed 5303823 and its merge with main (40aebfb). One inline finding and one about the PR body.

  1. The branch is not rebased onto #104. Merged with main, four tests in tests/test_tool_search.py fail because #104 removed Agent.messages. CI is green only because it ran before #104 merged. See the inline thread.
  2. The PR body still says "Search is stdlib word overlap, as Pydantic AI's default keywords strategy". Pydantic AI defaults to native search on Anthropic and OpenAI; keyword overlap is its local fallback. The Decisions section also says "Passing defer_loading through can follow once LiteLLM keeps those blocks", which leaves out the client-side tool_reference path that #113 now tracks; linking #113 there would match the guide. Refresh the test count after the rebase too.

The eight earlier threads are fixed in the code and docs:

  • The guide states the cache miss after a search and at the next run's first completion, and links #113 for Anthropic's and OpenAI's own search. #113 covers the tool_reference path, the LiteLLM fix in BerriAI/litellm#46440, and session-wide found tools.
  • Found tools staying per run is documented, in a session too.
  • Ranking sorts on (t in self.loaded, -score) with up to ten results.
  • The deny default note and its test are in the guide and the tests.
  • The MCPClient.attach docstring is rewrapped, and the tool_search import is in order.
  • New tests cover two searches in one step, ranking tools not loaded ahead of loaded ones, the ten result limit, and search_tools under a deny default.

I reran my probe on the merge with main. The results match the code: two searches in one step add each tool once, and a repeat search that overlaps lists the tool not yet loaded first. A deny default blocks search_tools, and a denied deferred tool is found and then refused. After #104, two sessionless runs each start from one message and the always-sent tools, and the second run of a session starts from the always-sent tools with the session's history. Per-run found-tool state matches both.

On 5303823 itself, uv run pytest (463 passed, 1 xfailed), pre-commit and mypy cyclops pass. The confidentiality grep and the dash check are clean over the title, body, commits, added lines and thread replies.

Comment thread tests/test_tool_search.py Resolved
Tools marked defer_loading are left out of the completions until the
model finds them with a search_tools tool, which matches keywords
against tool names and descriptions. Found tools are sent from the next
step to the end of the run. MCPClient.attach(defer_loading=True) defers
a server's tools.
A search now returns up to ten tools, tools not loaded yet ahead of
loaded ones. The guide states that a search that adds tools makes the
next completion miss the prompt cache, that found tools last for the
run, and that a deny default must allow search_tools.
@gopaljigaur

Copy link
Copy Markdown
Owner Author

PR body updated: the Pydantic AI comparison now says its default is native search on Anthropic and OpenAI, with keyword overlap as its local fallback; the Decisions line on client-side search names Anthropic's client-side tool_reference path and links #113; the test count is refreshed to 470 passed, 1 xfailed after the rebase (1e5f660).

@gopaljigaur gopaljigaur left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No findings.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Deferred tool loading through a search tool

1 participant