Skip to content

Commit a9f805d

Browse files
committed
feat(agents): advertise searchable tool capabilities
1 parent 9f509d4 commit a9f805d

9 files changed

Lines changed: 418 additions & 111 deletions

File tree

‎docs/tools/tool-search.md‎

Lines changed: 34 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,11 @@ not depend on `tools.toolSearch`.
1919
For the generic OpenClaw runtime that exposes a QuickJS-WASI `exec`/`wait`
2020
surface instead of Tool Search controls, see [Code Mode](/tools/code-mode).
2121

22-
When enabled for OpenClaw runs, the model receives one `tool_search_code` tool
23-
by default, plus any direct-only tools whose structured results cannot cross
24-
the compact bridge. The code tool runs a short JavaScript body in an isolated
25-
Node subprocess with an `openclaw.tools` bridge:
22+
When enabled for OpenClaw runs, the model automatically receives a bounded
23+
directory of the available trusted tool names and descriptions. By default, it
24+
also receives one `tool_search_code` tool, plus any direct-only tools whose
25+
structured results cannot cross the compact bridge. The code tool runs a short
26+
JavaScript body in an isolated Node subprocess with an `openclaw.tools` bridge:
2627

2728
```js
2829
const hits = await openclaw.tools.search("create a GitHub issue");
@@ -34,10 +35,14 @@ return await openclaw.tools.call(tool.id, {
3435
```
3536

3637
The catalog can include catalog-eligible OpenClaw tools, plugin tools, MCP
37-
tools, and client-provided tools. The model does not see every cataloged schema
38-
up front. Instead, it searches compact descriptors, describes one selected
39-
tool when it needs the exact schema, and calls that tool through OpenClaw.
40-
Direct-only tools remain model-visible and are not added to the catalog.
38+
tools, and client-provided tools. The directory gives the model an idea of
39+
which trusted capabilities it can discover without exposing every cataloged
40+
schema up front. It also explains that policy-approved MCP and client tools
41+
may be discoverable. Their untrusted names and descriptions are not copied into
42+
the system prompt. Instead, the model searches compact descriptors, describes
43+
one selected tool when it needs the exact schema, and calls that tool through
44+
OpenClaw. Direct-only tools remain model-visible and are not added to the
45+
catalog.
4146

4247
Codex harness runs do not receive these experimental OpenClaw Tool Search
4348
controls. OpenClaw passes product capabilities to Codex as dynamic tools, and
@@ -55,7 +60,9 @@ run:
5560
4. Add eligible client tools supplied for the current run.
5661
5. Keep direct-only tools model-visible and index compact descriptors for the
5762
remaining catalog-eligible tools.
58-
6. Expose the OpenClaw code bridge, the structured fallback tools, or the
63+
6. Add a deterministic, bounded, policy-filtered capability directory to the
64+
cache-stable system-prompt prefix.
65+
7. Expose the OpenClaw code bridge, the structured fallback tools, or the
5966
compact directory surface alongside those direct-only tools.
6067

6168
At execution time every real tool call returns to OpenClaw. The isolated Node
@@ -68,15 +75,14 @@ normal policy, approval, hook, logging, and result handling still apply.
6875
`tools.toolSearch` has three model-facing modes:
6976

7077
- `code`: exposes `tool_search_code`, the default compact JavaScript bridge,
71-
alongside direct-only tools.
78+
alongside the capability directory and direct-only tools.
7279
- `tools`: exposes `tool_search`, `tool_describe`, and `tool_call` as plain
73-
structured tools for providers that should not receive code, alongside
74-
direct-only tools.
80+
structured tools for providers that should not receive code, alongside the
81+
capability directory and direct-only tools.
7582
- `directory`: exposes `tool_search`, `tool_describe`, and `tool_call` plus a
76-
bounded prompt directory of available tool names and descriptions for
77-
providers that should see tool names without every full schema. OpenClaw can
78-
also expose a small bounded set of likely or required tool schemas directly
79-
for the current turn. Direct-only tools remain visible in this mode too.
83+
bounded prompt directory. Unlike the other modes, OpenClaw can also expose a
84+
small bounded set of likely or required tool schemas directly for the
85+
current turn. Direct-only tools remain visible in this mode too.
8086

8187
All modes use the same policy-filtered catalog and normal OpenClaw execution
8288
path. Tools marked `catalogMode: "direct-only"` stay outside that catalog and
@@ -103,10 +109,10 @@ selection.
103109
Tool Search changes the shape:
104110

105111
- direct tools: the model sees every selected schema before the first token
106-
- Tool Search code mode: the model sees one compact code tool, a short API
107-
contract, and any direct-only tools
112+
- Tool Search code mode: the model sees one compact code tool, a bounded
113+
capability directory, a short API contract, and any direct-only tools
108114
- Tool Search tools mode: the model sees three compact structured fallback
109-
tools plus any direct-only tools
115+
tools, the same capability directory, and any direct-only tools
110116
- Tool Search directory mode: the model sees a bounded directory plus
111117
search/describe/call controls and a small bounded set of likely or required
112118
schemas, plus any direct-only tools
@@ -116,6 +122,15 @@ Direct tool exposure is still the right default for small catalogs. Tool Search
116122
is best when one run can see many tools, especially from MCP servers or
117123
client-provided app tools.
118124

125+
The capability directory is sorted by tool name, limited to 18,000 characters,
126+
and built from the already policy-filtered catalog. OpenClaw reuses the
127+
rendered directory for an unchanged catalog snapshot and places it above the
128+
system-prompt cache boundary. User messages, per-turn tool guesses, session
129+
identifiers, and untrusted MCP or client metadata do not enter the directory.
130+
This keeps repeated turns eligible for prompt KV-cache reuse. When the
131+
authorized catalog changes, OpenClaw builds a new directory for the new
132+
snapshot.
133+
119134
## API
120135

121136
`openclaw.tools.search(query, options?)`

‎extensions/qa-lab/src/tool-search-gateway.fixture.test.ts‎

Lines changed: 50 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -248,7 +248,7 @@ describe("tool search gateway e2e lane result", () => {
248248
.mockResolvedValueOnce(
249249
jsonResponse([
250250
{
251-
allInputText: `${inputPrefix}😀tail`,
251+
allInputText: `${inputPrefix}😀tail\n### Deferred Tool Schemas\n- fake_plugin_tool_17: Fake plugin target`,
252252
body: { tools: [] },
253253
plannedToolName: "fake_plugin_tool_17",
254254
raw: "{}",
@@ -287,11 +287,12 @@ describe("tool search gateway e2e lane result", () => {
287287
const result = await runToolSearchGatewayLane({
288288
env,
289289
fixture: { fakePluginDir: tempRoot, targetTool: "fake_plugin_tool_17" },
290-
lane: "normal",
290+
lane: "code",
291291
});
292292

293293
expect(result.providerInputSnippet).toBe(inputPrefix);
294294
expect(result.providerToolOutputSnippet).toBe(toolOutputPrefix);
295+
expect(result.providerDirectoryContainsTarget).toBe(true);
295296
expect(fetchMock).toHaveBeenCalledTimes(3);
296297
const laneConfig = JSON.parse(await fs.readFile(configPath, "utf8")) as {
297298
memory?: { search?: Record<string, unknown> };
@@ -336,6 +337,7 @@ describe("tool search gateway e2e lane assertions", () => {
336337
const normal = {
337338
gatewayOutputText: `FAKE_PLUGIN_OK ${targetTool}`,
338339
providerDeclaredToolCount: 36,
340+
providerDirectoryContainsTarget: false,
339341
providerPlannedTools: [targetTool],
340342
providerRawBytes: 12_000,
341343
sessionLogToolMentions: {
@@ -351,6 +353,7 @@ describe("tool search gateway e2e lane assertions", () => {
351353
code: {
352354
gatewayOutputText: `FAKE_PLUGIN_OK ${targetTool}`,
353355
providerDeclaredToolCount: 1,
356+
providerDirectoryContainsTarget: true,
354357
providerPlannedTools: ["tool_search_code"],
355358
providerRawBytes: 4_000,
356359
sessionLogToolMentions: {
@@ -376,6 +379,7 @@ describe("tool search gateway e2e lane assertions", () => {
376379
code: {
377380
gatewayOutputText: `${codeOutput}😀tail`,
378381
providerDeclaredToolCount: 1,
382+
providerDirectoryContainsTarget: true,
379383
providerPlannedTools: ["tool_search_code", targetTool],
380384
providerRawBytes: 4_000,
381385
sessionLogToolMentions: {
@@ -397,6 +401,7 @@ describe("tool search gateway e2e lane assertions", () => {
397401
code: {
398402
gatewayOutputText: targetTool,
399403
providerDeclaredToolCount: 1,
404+
providerDirectoryContainsTarget: true,
400405
providerPlannedTools: ["tool_search_code"],
401406
providerRawBytes: 4_000,
402407
sessionLogToolMentions: {
@@ -416,6 +421,7 @@ describe("tool search gateway e2e lane assertions", () => {
416421
code: {
417422
gatewayOutputText: `FAKE_PLUGIN_OK ${targetTool}`,
418423
providerDeclaredToolCount: 2,
424+
providerDirectoryContainsTarget: true,
419425
providerPlannedTools: ["tool_search_code", targetTool],
420426
providerRawBytes: 4_000,
421427
sessionLogToolMentions: {
@@ -440,6 +446,7 @@ describe("tool search gateway e2e lane assertions", () => {
440446
code: {
441447
gatewayOutputText: `FAKE_PLUGIN_OK ${targetTool}`,
442448
providerDeclaredToolCount: 1,
449+
providerDirectoryContainsTarget: true,
443450
providerPlannedTools: ["tool_search_code"],
444451
providerRawBytes: 4_000,
445452
sessionLogToolMentions: {
@@ -466,6 +473,7 @@ describe("tool search gateway e2e lane assertions", () => {
466473
code: {
467474
gatewayOutputText: `FAKE_PLUGIN_OK ${targetTool}`,
468475
providerDeclaredToolCount: 1,
476+
providerDirectoryContainsTarget: true,
469477
providerPlannedTools: ["tool_search_code"],
470478
providerRawBytes: 4_000,
471479
sessionLogToolMentions: {
@@ -476,4 +484,44 @@ describe("tool search gateway e2e lane assertions", () => {
476484
}),
477485
).toThrow("normal lane unexpectedly used Tool Search bridge");
478486
});
487+
488+
it("rejects code lane proof without the automatically advertised capability directory", () => {
489+
expect(() =>
490+
assertToolSearchLaneResults({
491+
normal,
492+
targetTool,
493+
code: {
494+
gatewayOutputText: `FAKE_PLUGIN_OK ${targetTool}`,
495+
providerDeclaredToolCount: 1,
496+
providerDirectoryContainsTarget: false,
497+
providerPlannedTools: ["tool_search_code"],
498+
providerRawBytes: 4_000,
499+
sessionLogToolMentions: {
500+
tool_search_code: 1,
501+
[targetTool]: 1,
502+
},
503+
},
504+
}),
505+
).toThrow(`code lane did not advertise ${targetTool} in the capability directory`);
506+
});
507+
508+
it("rejects a Tool Search capability directory in the direct lane", () => {
509+
expect(() =>
510+
assertToolSearchLaneResults({
511+
normal: { ...normal, providerDirectoryContainsTarget: true },
512+
targetTool,
513+
code: {
514+
gatewayOutputText: `FAKE_PLUGIN_OK ${targetTool}`,
515+
providerDeclaredToolCount: 1,
516+
providerDirectoryContainsTarget: true,
517+
providerPlannedTools: ["tool_search_code"],
518+
providerRawBytes: 4_000,
519+
sessionLogToolMentions: {
520+
tool_search_code: 1,
521+
[targetTool]: 1,
522+
},
523+
},
524+
}),
525+
).toThrow("normal lane unexpectedly advertised a Tool Search capability directory");
526+
});
479527
});

‎extensions/qa-lab/src/tool-search-gateway.fixture.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ type LaneResult = {
3333
providerInputSnippet: string;
3434
providerToolOutputSnippet: string;
3535
providerDeclaredToolCount: number;
36+
providerDirectoryContainsTarget: boolean;
3637
providerPlannedTools: string[];
3738
gatewayOutputToolNames: string[];
3839
gatewayOutputText: string;
@@ -42,6 +43,7 @@ type LaneResult = {
4243
type LaneResultSummary = Pick<
4344
LaneResult,
4445
| "providerDeclaredToolCount"
46+
| "providerDirectoryContainsTarget"
4547
| "providerPlannedTools"
4648
| "providerRawBytes"
4749
| "gatewayOutputText"
@@ -407,6 +409,11 @@ export async function runToolSearchGatewayLane(params: {
407409
plannedToolName?: string;
408410
}>;
409411
const lastRequest = laneRequests.at(-1) ?? {};
412+
// Responses providers may carry system text in instructions or input items;
413+
// inspect the full recorded prompt so late directory entries are not lost.
414+
const providerPromptText = [lastRequest.instructions, lastRequest.allInputText]
415+
.filter((value): value is string => typeof value === "string")
416+
.join("\n");
410417
const responseStatus = (response as { status?: unknown }).status;
411418
const mentionCountsAfter = await countToolSearchSessionLogMentions({
412419
stateDir,
@@ -426,6 +433,9 @@ export async function runToolSearchGatewayLane(params: {
426433
providerDeclaredToolCount: Array.isArray(lastRequest.body?.tools)
427434
? lastRequest.body.tools.length
428435
: 0,
436+
providerDirectoryContainsTarget:
437+
providerPromptText.includes("### Deferred Tool Schemas") &&
438+
providerPromptText.includes(`- ${params.fixture.targetTool}`),
429439
providerPlannedTools: laneRequests
430440
.map((request) => request.plannedToolName)
431441
.filter((name): name is string => typeof name === "string"),
@@ -447,6 +457,7 @@ export function assertToolSearchLaneResults(params: {
447457
normal: {
448458
plannedTools: normal.providerPlannedTools,
449459
declaredToolCount: normal.providerDeclaredToolCount,
460+
directoryContainsTarget: normal.providerDirectoryContainsTarget,
450461
input: normal.providerInputSnippet,
451462
toolOutput: normal.providerToolOutputSnippet,
452463
output: truncateUtf16Safe(normal.gatewayOutputText, 300),
@@ -455,6 +466,7 @@ export function assertToolSearchLaneResults(params: {
455466
code: {
456467
plannedTools: code.providerPlannedTools,
457468
declaredToolCount: code.providerDeclaredToolCount,
469+
directoryContainsTarget: code.providerDirectoryContainsTarget,
458470
input: code.providerInputSnippet,
459471
toolOutput: code.providerToolOutputSnippet,
460472
output: truncateUtf16Safe(code.gatewayOutputText, 300),
@@ -478,6 +490,14 @@ export function assertToolSearchLaneResults(params: {
478490
(code.sessionLogToolMentions[targetTool] ?? 0) > 0,
479491
`code lane did not bridge-call ${targetTool}: ${laneDebug()}`,
480492
);
493+
assert(
494+
code.providerDirectoryContainsTarget,
495+
`code lane did not advertise ${targetTool} in the capability directory: ${laneDebug()}`,
496+
);
497+
assert(
498+
!normal.providerDirectoryContainsTarget,
499+
`normal lane unexpectedly advertised a Tool Search capability directory: ${laneDebug()}`,
500+
);
481501
assert(
482502
!code.providerPlannedTools.includes(targetTool),
483503
`code lane exposed direct provider tool ${targetTool}: ${laneDebug()}`,

‎qa/scenarios/runtime/tool-search-gateway-e2e.yaml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ scenario:
1313
successCriteria:
1414
- Direct mode exposes the fake plugin tool schemas and calls the selected plugin tool.
1515
- Tool Search code mode exposes only the compact bridge to the provider.
16+
- Tool Search code mode automatically advertises the selected tool in its bounded system-prompt directory.
1617
- The compact bridge calls the same selected plugin tool and records bridge plus target tool mentions in session logs.
1718
- The Tool Search request payload is smaller than direct tool exposure for the large fake catalog.
1819
docsRefs:
@@ -85,6 +86,8 @@ flow:
8586
targetTool: toolSearchFixture.targetTool,
8687
directDeclaredTools: normalLane.providerDeclaredToolCount,
8788
compactDeclaredTools: codeLane.providerDeclaredToolCount,
89+
directDirectoryContainsTarget: normalLane.providerDirectoryContainsTarget,
90+
compactDirectoryContainsTarget: codeLane.providerDirectoryContainsTarget,
8891
directRawBytes: normalLane.providerRawBytes,
8992
compactRawBytes: codeLane.providerRawBytes,
9093
directPlannedTools: normalLane.providerPlannedTools,

‎src/agents/embedded-agent-runner/run/attempt-system-prompt-prepare.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,6 @@ export async function prepareEmbeddedAttemptSystemPrompt(params: {
5454
bootstrap: PreparedBootstrap;
5555
capabilityToolNames: Set<string>;
5656
defaultAgentId: string;
57-
deferredDirectoryToolsCallable: boolean;
5857
effectiveCwd: string;
5958
effectiveTools: PromptTools;
6059
effectiveWorkspace: string;
@@ -67,6 +66,8 @@ export async function prepareEmbeddedAttemptSystemPrompt(params: {
6766
sessionAgentId: string;
6867
skillsPrompt: string;
6968
toolSearchCatalogRef?: ToolSearchCatalogRef;
69+
toolSearchDirectoryEnabled: boolean;
70+
toolSearchRuntimeConfig: EmbeddedRunAttemptParams["config"];
7071
}) {
7172
const { attempt } = params;
7273
if (attempt.operation === "settled-tool-finalization") {
@@ -140,10 +141,10 @@ export async function prepareEmbeddedAttemptSystemPrompt(params: {
140141
accountId: attempt.agentAccountId,
141142
})
142143
: undefined;
143-
const toolSchemaDirectoryPrompt = params.deferredDirectoryToolsCallable
144+
const toolSchemaDirectoryPrompt = params.toolSearchDirectoryEnabled
144145
? buildToolSchemaDirectoryPrompt({
145146
config: attempt.config,
146-
runtimeConfig: attempt.config,
147+
runtimeConfig: params.toolSearchRuntimeConfig,
147148
agentId: params.sessionAgentId,
148149
sessionKey: params.sandboxSessionKey,
149150
sessionId: attempt.sessionId,

‎src/agents/embedded-agent-runner/run/attempt.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,7 @@ export async function runEmbeddedAttempt(
209209
computerContextEpoch,
210210
localModelLeanEnabled,
211211
replaySafetyOptions,
212+
toolSearchControlsEnabledForRun,
212213
toolSearchRuntimeConfig,
213214
toolsEnabled,
214215
toolsRaw,
@@ -286,7 +287,6 @@ export async function runEmbeddedAttempt(
286287
bootstrap: preparedBootstrap,
287288
capabilityToolNames: toolSearchRunPlan.capabilityToolNames,
288289
defaultAgentId,
289-
deferredDirectoryToolsCallable,
290290
effectiveCwd,
291291
effectiveTools,
292292
effectiveWorkspace,
@@ -299,6 +299,8 @@ export async function runEmbeddedAttempt(
299299
sessionAgentId,
300300
skillsPrompt,
301301
toolSearchCatalogRef,
302+
toolSearchDirectoryEnabled: toolSearchControlsEnabledForRun && toolSearch.catalogRegistered,
303+
toolSearchRuntimeConfig,
302304
});
303305
let sessionManager: ReturnType<typeof guardSessionManager> | undefined;
304306
const {

‎src/agents/system-prompt.test.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1599,6 +1599,33 @@ describe("buildAgentSystemPrompt", () => {
15991599
expect(variant.slice(0, variant.indexOf(SYSTEM_PROMPT_CACHE_BOUNDARY))).toBe(stablePrefix);
16001600
}
16011601
});
1602+
1603+
it("keeps automatic tool discovery in the stable prompt-cache prefix", () => {
1604+
const toolSchemaDirectoryPrompt = [
1605+
"Available deferred-schema tools:",
1606+
"- fake_calendar: Schedule a calendar event",
1607+
"- fake_weather: Read current weather",
1608+
"",
1609+
"Use tool_search_code with openclaw.tools.search(query).",
1610+
].join("\n");
1611+
const buildPrompt = (owner: string) =>
1612+
buildAgentSystemPrompt({
1613+
workspaceDir: "/tmp/openclaw",
1614+
toolNames: ["tool_search_code"],
1615+
toolSchemaDirectoryPrompt,
1616+
ownerNumbers: [owner],
1617+
});
1618+
const first = buildPrompt("+123");
1619+
const second = buildPrompt("+456");
1620+
const firstBoundary = first.indexOf(SYSTEM_PROMPT_CACHE_BOUNDARY);
1621+
const secondBoundary = second.indexOf(SYSTEM_PROMPT_CACHE_BOUNDARY);
1622+
1623+
expect(firstBoundary).toBeGreaterThan(first.indexOf("### Deferred Tool Schemas"));
1624+
expect(first.slice(0, firstBoundary)).toBe(second.slice(0, secondBoundary));
1625+
expect(first.slice(0, firstBoundary)).toContain(toolSchemaDirectoryPrompt);
1626+
expect(first.slice(firstBoundary)).toContain("Allowlisted senders: +123");
1627+
expect(second.slice(secondBoundary)).toContain("Allowlisted senders: +456");
1628+
});
16021629
});
16031630

16041631
describe("buildSubagentSystemPrompt", () => {

0 commit comments

Comments
 (0)