Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(tools): tool search (#4264)

Eric Hayesab8af5dee4bf
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index db6ae361b0..4ccff78433 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -14,6 +14,7 @@
"model_file_type",
"model_user",
"non_empty",
+ "prompt",
"workspace-hack"
],
"ai_projections": [
@@ -147,6 +148,7 @@
"models_pagination",
"models_permissions",
"non_empty",
+ "prompt",
"remote_env_var",
"s3_key",
"sqs_client",
@@ -365,6 +367,7 @@
"notification",
"opensearch_client",
"opensearch_query_builder",
+ "prompt",
"rate_limit",
"referral",
"remote_env_var",
@@ -405,6 +408,7 @@
"models_pagination",
"models_permissions",
"non_empty",
+ "prompt",
"workspace-hack"
],
"backfill_entity_access": [
@@ -472,6 +476,7 @@
"models_team",
"non_empty",
"notification",
+ "prompt",
"rate_limit",
"remote_env_var",
"s3_key",
@@ -544,6 +549,7 @@
"models_team",
"non_empty",
"notification",
+ "prompt",
"rate_limit",
"remote_env_var",
"s3_key",
@@ -711,6 +717,7 @@
"models_team",
"non_empty",
"notification",
+ "prompt",
"rate_limit",
"remote_env_var",
"s3_key",
@@ -746,6 +753,7 @@
"models_pagination",
"models_permissions",
"non_empty",
+ "prompt",
"roles_and_permissions",
"workspace-hack"
],
@@ -802,6 +810,7 @@
"models_team",
"non_empty",
"notification",
+ "prompt",
"rate_limit",
"remote_env_var",
"s3_key",
@@ -836,6 +845,7 @@
"models_pagination",
"models_permissions",
"non_empty",
+ "prompt",
"workspace-hack"
],
"connection_gateway": [
@@ -881,6 +891,7 @@
"models_properties",
"models_team",
"non_empty",
+ "prompt",
"remote_env_var",
"secretsmanager_client",
"stream",
@@ -933,6 +944,7 @@
"models_properties",
"models_team",
"non_empty",
+ "prompt",
"rate_limit",
"remote_env_var",
"sqs_worker",
@@ -980,6 +992,7 @@
"models_properties",
"models_team",
"non_empty",
+ "prompt",
"rate_limit",
"remote_env_var",
"secretsmanager_client",
@@ -1037,6 +1050,7 @@
"models_properties",
"models_team",
"non_empty",
+ "prompt",
"remote_env_var",
"s3_client",
"s3_key",
@@ -1073,6 +1087,7 @@
"models_pagination",
"models_permissions",
"non_empty",
+ "prompt",
"unfurl",
"workspace-hack"
],
@@ -1151,6 +1166,7 @@
"models_properties",
"models_team",
"non_empty",
+ "prompt",
"s3_key",
"sqs_client",
"system_properties",
@@ -1401,6 +1417,7 @@
"models_pagination",
"models_permissions",
"non_empty",
+ "prompt",
"workspace-hack"
],
"document_sub_type": [
@@ -1430,6 +1447,7 @@
"models_pagination",
"models_permissions",
"non_empty",
+ "prompt",
"s3_key",
"workspace-hack"
],
@@ -1500,6 +1518,7 @@
"notification",
"opensearch_client",
"opensearch_query_builder",
+ "prompt",
"rate_limit",
"remote_env_var",
"s3_key",
@@ -1581,6 +1600,7 @@
"notification",
"opensearch_client",
"opensearch_query_builder",
+ "prompt",
"rate_limit",
"remote_env_var",
"s3_key",
@@ -1638,6 +1658,7 @@
"models_properties",
"models_team",
"non_empty",
+ "prompt",
"s3_client",
"s3_key",
"sqs_client",
@@ -1681,6 +1702,7 @@
"models_pagination",
"models_permissions",
"non_empty",
+ "prompt",
"unfurl",
"workspace-hack"
],
@@ -1752,6 +1774,7 @@
"models_pagination",
"models_permissions",
"non_empty",
+ "prompt",
"s3_key",
"sqs_client",
"unfurl",
@@ -1790,6 +1813,7 @@
"models_pagination",
"models_permissions",
"non_empty",
+ "prompt",
"s3_key",
"sqs_client",
"unfurl",
@@ -1853,6 +1877,7 @@
"models_team",
"non_empty",
"notification",
+ "prompt",
"rate_limit",
"remote_env_var",
"s3_client",
@@ -1895,6 +1920,7 @@
"models_pagination",
"models_permissions",
"non_empty",
+ "prompt",
"unfurl",
"workspace-hack"
],
@@ -1931,6 +1957,7 @@
"models_pagination",
"models_permissions",
"non_empty",
+ "prompt",
"s3_key",
"sqs_client",
"unfurl",
@@ -1965,6 +1992,7 @@
"models_properties",
"models_team",
"non_empty",
+ "prompt",
"system_properties",
"user_quota",
"workspace-hack"
@@ -2005,6 +2033,7 @@
"models_pagination",
"models_permissions",
"non_empty",
+ "prompt",
"workspace-hack"
],
"entity_access_db_utils": [
@@ -2057,6 +2086,7 @@
"models_pagination",
"models_permissions",
"non_empty",
+ "prompt",
"workspace-hack"
],
"frecency": [
@@ -2145,6 +2175,7 @@
"notification",
"opensearch_client",
"opensearch_query_builder",
+ "prompt",
"rate_limit",
"remote_env_var",
"s3_key",
@@ -2215,6 +2246,7 @@
"models_properties",
"models_team",
"non_empty",
+ "prompt",
"remote_env_var",
"secretsmanager_client",
"system_properties",
@@ -2327,6 +2359,7 @@
"notification",
"opensearch_client",
"opensearch_query_builder",
+ "prompt",
"rate_limit",
"remote_env_var",
"s3_key",
@@ -2423,6 +2456,7 @@
"models_properties",
"models_team",
"non_empty",
+ "prompt",
"system_properties",
"user_quota",
"workspace-hack"
@@ -2477,6 +2511,7 @@
"models_properties",
"models_team",
"non_empty",
+ "prompt",
"remote_env_var",
"system_properties",
"user_quota",
@@ -2516,6 +2551,7 @@
"models_pagination",
"models_permissions",
"non_empty",
+ "prompt",
"workspace-hack"
],
"macro_tower_layers": [
@@ -2557,6 +2593,7 @@
"model_file_type",
"model_user",
"non_empty",
+ "prompt",
"workspace-hack"
],
"mcp_service": [
@@ -2782,6 +2819,7 @@
"models_pagination",
"models_permissions",
"non_empty",
+ "prompt",
"workspace-hack"
],
"model-entity": [
@@ -2934,6 +2972,7 @@
"notification",
"opensearch_client",
"opensearch_query_builder",
+ "prompt",
"rate_limit",
"remote_env_var",
"s3_key",
@@ -3009,6 +3048,7 @@
"models_team",
"non_empty",
"notification",
+ "prompt",
"rate_limit",
"remote_env_var",
"s3_key",
@@ -3164,6 +3204,7 @@
"notification",
"notification_db_client",
"notification_service",
+ "prompt",
"rate_limit",
"remote_env_var",
"secretsmanager_client",
@@ -3216,6 +3257,7 @@
"models_permissions",
"non_empty",
"organization_retention_handler",
+ "prompt",
"s3_key",
"sqs_client",
"unfurl",
@@ -3254,6 +3296,7 @@
"models_permissions",
"non_empty",
"organization_retention_trigger",
+ "prompt",
"s3_key",
"sqs_client",
"unfurl",
@@ -3302,6 +3345,7 @@
"models_team",
"non_empty",
"notification",
+ "prompt",
"properties",
"rate_limit",
"remote_env_var",
@@ -3357,6 +3401,7 @@
"models_team",
"non_empty",
"notification",
+ "prompt",
"properties",
"properties_db_client",
"properties_service",
@@ -3589,6 +3634,7 @@
"notification",
"opensearch_client",
"opensearch_query_builder",
+ "prompt",
"properties_db_client",
"rate_limit",
"remote_env_var",
@@ -3667,6 +3713,7 @@
"notification",
"opensearch_client",
"opensearch_query_builder",
+ "prompt",
"properties_db_client",
"rate_limit",
"readonly_pool",
@@ -3742,6 +3789,7 @@
"notification",
"opensearch_client",
"opensearch_query_builder",
+ "prompt",
"rate_limit",
"remote_env_var",
"s3_key",
@@ -3788,6 +3836,7 @@
"models_pagination",
"models_permissions",
"non_empty",
+ "prompt",
"s3_key",
"search_upload_handler",
"sqs_client",
@@ -3858,6 +3907,7 @@
"models_team",
"non_empty",
"notification",
+ "prompt",
"rate_limit",
"remote_env_var",
"s3_key",
@@ -3960,6 +4010,7 @@
"models_team",
"non_empty",
"notification",
+ "prompt",
"properties_db_client",
"rate_limit",
"readonly_pool",
@@ -4003,6 +4054,7 @@
"models_pagination",
"models_permissions",
"non_empty",
+ "prompt",
"s3_key",
"sqs_client",
"unfurl",
@@ -4060,6 +4112,7 @@
"models_sfs",
"models_team",
"non_empty",
+ "prompt",
"remote_env_var",
"s3_key",
"secretsmanager_client",
@@ -4102,6 +4155,7 @@
"models_pagination",
"models_permissions",
"non_empty",
+ "prompt",
"sync_service",
"sync_service_client",
"workspace-hack"
@@ -4178,6 +4232,7 @@
"notification",
"opensearch_client",
"opensearch_query_builder",
+ "prompt",
"rate_limit",
"remote_env_var",
"s3_key",
@@ -4229,6 +4284,7 @@
"models_permissions",
"non_empty",
"notification",
+ "prompt",
"rate_limit",
"remote_env_var",
"roles_and_permissions",
@@ -4291,6 +4347,7 @@
"models_pagination",
"models_permissions",
"non_empty",
+ "prompt",
"s3_key",
"sqs_client",
"unfurl",
@@ -4330,6 +4387,7 @@
"models_pagination",
"models_permissions",
"non_empty",
+ "prompt",
"s3_key",
"sqs_client",
"unfurl",
@@ -4364,6 +4422,7 @@
"models_properties",
"models_team",
"non_empty",
+ "prompt",
"system_properties",
"user_link_cleanup_handler",
"user_quota",
diff --git a/js/app/packages/core/component/AI/component/tool/LoadTools.tsx b/js/app/packages/core/component/AI/component/tool/LoadTools.tsx
new file mode 100644
index 0000000000..9edd24da40
--- /dev/null
+++ b/js/app/packages/core/component/AI/component/tool/LoadTools.tsx
@@ -0,0 +1,29 @@
+import Plus from '@phosphor-icons/core/regular/plus.svg';
+import { Show } from 'solid-js';
+import { BaseTool } from './BaseTool';
+import { createToolRenderer } from './ToolRenderer';
+
+const handler = createToolRenderer({
+ name: 'LoadTools',
+ render: (ctx) => {
+ const count = () => ctx.response?.data.loaded.length ?? 0;
+ const countText = () => {
+ if (count() === 0) return 'No tools loaded';
+ if (count() === 1) return '1 tool loaded';
+ return `${count()} tools loaded`;
+ };
+
+ return (
+ <BaseTool icon={Plus} renderContext={ctx.renderContext} type="call">
+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3 overflow-hidden">
+ <span class="min-w-0 truncate">Loaded tools</span>
+ <Show when={ctx.response}>
+ <span class="shrink-0 text-ink-extra-muted">{countText()}</span>
+ </Show>
+ </div>
+ </BaseTool>
+ );
+ },
+});
+
+export const loadToolsHandler = handler;
diff --git a/js/app/packages/core/component/AI/component/tool/SearchTools.tsx b/js/app/packages/core/component/AI/component/tool/SearchTools.tsx
new file mode 100644
index 0000000000..f95225920e
--- /dev/null
+++ b/js/app/packages/core/component/AI/component/tool/SearchTools.tsx
@@ -0,0 +1,36 @@
+import MagnifyingGlass from '@phosphor-icons/core/regular/magnifying-glass.svg';
+import { Show } from 'solid-js';
+import { BaseTool } from './BaseTool';
+import { createToolRenderer } from './ToolRenderer';
+
+const handler = createToolRenderer({
+ name: 'SearchTools',
+ render: (ctx) => {
+ const count = () => ctx.response?.data.results.length ?? 0;
+ const countText = () => {
+ if (count() === 0) return 'No tools found';
+ if (count() === 1) return '1 tool found';
+ return `${count()} tools found`;
+ };
+
+ return (
+ <BaseTool
+ icon={MagnifyingGlass}
+ renderContext={ctx.renderContext}
+ type="call"
+ >
+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3 overflow-hidden">
+ <span class="min-w-0 truncate">
+ Searched tools for{' '}
+ <span class="text-ink">{ctx.tool.data.query}</span>
+ </span>
+ <Show when={ctx.response}>
+ <span class="shrink-0 text-ink-extra-muted">{countText()}</span>
+ </Show>
+ </div>
+ </BaseTool>
+ );
+ },
+});
+
+export const searchToolsHandler = handler;
diff --git a/js/app/packages/core/component/AI/component/tool/handler.tsx b/js/app/packages/core/component/AI/component/tool/handler.tsx
index ac5226becb..1971dee2e4 100644
--- a/js/app/packages/core/component/AI/component/tool/handler.tsx
+++ b/js/app/packages/core/component/AI/component/tool/handler.tsx
@@ -12,6 +12,7 @@ import { listCallRecordsHandler } from './ListCallRecords';
import { listEntitiesHandler } from './ListEntities';
import { listLabelsHandler } from './ListLabels';
import { listTeamMembersHandler } from './ListTeamMembers';
+import { loadToolsHandler } from './LoadTools';
import {
listNotificationsHandler,
markNotificationsDoneHandler,
@@ -33,6 +34,7 @@ import { readMetadataHandler } from './ReadMetadata';
import { readThreadHandler } from './ReadThread';
import { renameDocumentHandler } from './RenameDocument';
import { contentSearchHandler, nameSearchHandler } from './Search';
+import { searchToolsHandler } from './SearchTools';
import { sendEmailHandler } from './SendEmail';
import { subagentHandler } from './Subagent';
import { textEditorCodeExecutionHandler } from './TextEditorCodeExecution';
@@ -54,6 +56,7 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {
ListLabels: listLabelsHandler,
ListNotifications: listNotificationsHandler,
ListTeamMembers: listTeamMembersHandler,
+ LoadTools: loadToolsHandler,
MarkNotificationsDone: markNotificationsDoneHandler,
MarkNotificationsSeen: markNotificationsSeenHandler,
BashCodeExecution: bashCodeExecutionHandler,
@@ -71,6 +74,7 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {
ReadContent: readContentHandler,
ReadMetadata: readMetadataHandler,
RenameDocument: renameDocumentHandler,
+ SearchTools: searchToolsHandler,
SendEmail: sendEmailHandler,
SetEntityProperty: setEntityPropertyHandler,
Subagent: subagentHandler,
diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts
index a54a9c958f..36bdbfb8e8 100644
--- a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts
+++ b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts
@@ -795,6 +795,13 @@ export const ListTeamMembersResponse = z.object({
members: z.array(z.object({ role: z.string(), userId: z.string() })),
});
+export const LoadTools = z.object({ names: z.array(z.string()) });
+
+export const LoadToolsResponse = z.object({
+ loaded: z.array(z.object({ description: z.string(), name: z.string() })),
+ not_found: z.array(z.string()),
+});
+
export const MarkNotificationsDone = z.object({
done: z.boolean(),
notificationIds: z.array(z.string().uuid()),
@@ -1898,6 +1905,12 @@ export const RenameDocumentResponse = z.object({
success: z.boolean(),
});
+export const SearchTools = z.object({ query: z.string() });
+
+export const SearchToolsResponse = z.object({
+ results: z.array(z.object({ description: z.string(), name: z.string() })),
+});
+
export const SendEmail = z.object({
bcc: z
.array(
diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts b/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts
index 3f3ea010b6..bdc90bd556 100644
--- a/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts
+++ b/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts
@@ -46,6 +46,7 @@ type ToolParserMap = {
call: types.ListTeamMembers;
response: types.ListTeamMembersResponse;
};
+ LoadTools: { call: types.LoadTools; response: types.LoadToolsResponse };
MarkNotificationsDone: {
call: types.MarkNotificationsDone;
response: types.MarkNotificationsResponse;
@@ -82,6 +83,7 @@ type ToolParserMap = {
call: types.RenameDocument;
response: types.RenameDocumentResponse;
};
+ SearchTools: { call: types.SearchTools; response: types.SearchToolsResponse };
SendEmail: { call: types.SendEmail; response: types.UserToolResponse };
SetEntityProperty: {
call: types.SetEntityProperty;
@@ -142,6 +144,7 @@ const toolParserMap = {
call: schemas.ListTeamMembers,
response: schemas.ListTeamMembersResponse,
},
+ LoadTools: { call: schemas.LoadTools, response: schemas.LoadToolsResponse },
MarkNotificationsDone: {
call: schemas.MarkNotificationsDone,
response: schemas.MarkNotificationsResponse,
@@ -184,6 +187,10 @@ const toolParserMap = {
call: schemas.RenameDocument,
response: schemas.RenameDocumentResponse,
},
+ SearchTools: {
+ call: schemas.SearchTools,
+ response: schemas.SearchToolsResponse,
+ },
SendEmail: { call: schemas.SendEmail, response: schemas.UserToolResponse },
SetEntityProperty: {
call: schemas.SetEntityProperty,
@@ -249,6 +256,7 @@ type ToolDataMap = {
call: types.ListTeamMembers;
response: types.ListTeamMembersResponse;
};
+ LoadTools: { call: types.LoadTools; response: types.LoadToolsResponse };
MarkNotificationsDone: {
call: types.MarkNotificationsDone;
response: types.MarkNotificationsResponse;
@@ -285,6 +293,7 @@ type ToolDataMap = {
call: types.RenameDocument;
response: types.RenameDocumentResponse;
};
+ SearchTools: { call: types.SearchTools; response: types.SearchToolsResponse };
SendEmail: { call: types.SendEmail; response: types.UserToolResponse };
SetEntityProperty: {
call: types.SetEntityProperty;
diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts b/js/app/packages/service-clients/service-cognition/generated/tools/types.ts
index b004b00fa9..45a1a028c9 100644
--- a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts
+++ b/js/app/packages/service-clients/service-cognition/generated/tools/types.ts
@@ -1632,6 +1632,43 @@ export interface ToolTeamMember {
*/
userId: string;
}
+/**
+ * Load tools by name (from `SearchTools` results) so you can call them. After loading, invoke each tool by its name. Only load the tools you actually need.
+ */
+export interface LoadTools {
+ /**
+ * Exact tool names to load, taken from SearchTools results.
+ */
+ names: string[];
+}
+/**
+ * Response from [`LoadTools`]: which requested tools were loaded, and any names
+ * that weren't found.
+ */
+export interface LoadToolsResponse {
+ /**
+ * Tools that are now loaded and callable by name.
+ */
+ loaded: ToolMatch[];
+ /**
+ * Requested names that don't exist (call `SearchTools` to find valid names).
+ */
+ not_found: string[];
+}
+/**
+ * A tool surfaced by [`SearchTools`] or loaded by [`LoadTools`] — just enough
+ * for the model to decide whether to load it and how to call it.
+ */
+export interface ToolMatch {
+ /**
+ * What the tool does.
+ */
+ description: string;
+ /**
+ * The exact name to load and then call the tool by.
+ */
+ name: string;
+}
/**
* Mark one or more notifications as done or not done for the current user. Use this when the user has completed the action associated with a notification.
*/
@@ -2471,6 +2508,25 @@ export interface RenameDocumentResponse {
export interface SearchToolResponse {
results: UnifiedSearchResponseItem[];
}
+/**
+ * Find tools from connected integrations (e.g. Slack, Gmail, Linear, GitHub) by keyword. Returns matching tools' names and descriptions but does NOT load them — pass the names you want to `LoadTools` to make them callable. Searching is cheap, so cast a wide net.
+ */
+export interface SearchTools {
+ /**
+ * Keywords describing the capability you need, e.g. "linear issue" or "github list commits".
+ */
+ query: string;
+}
+/**
+ * Response from [`SearchTools`]: matching tools (name + description), not yet
+ * loaded.
+ */
+export interface SearchToolsResponse {
+ /**
+ * Tools matching the query. Call `LoadTools` with the names you want to use.
+ */
+ results: ToolMatch[];
+}
/**
* Draft, compose, and send an email. ALWAYS use this tool whenever the user asks you to draft, write, compose, or send an email (or reply to one) — never write the email as plain text in the chat. This tool opens the email draft in the composer for the user to review, edit, and confirm before it is sent, so it is the correct tool even when the user only wants a draft. To reply to an existing message, provide the replying_to_id. Write the body in Markdown — use **bold**, *italics*, lists, links, and other standard Markdown formatting. The draft composer renders the Markdown for the user to review and edit; the composer produces HTML that is sent as the actual email body.
*/
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 858ff46a11..e9188877c9 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -59,6 +59,7 @@ dependencies = [
"macro_user_id",
"model-entity",
"non_empty",
+ "prompt",
"regex",
"rig-core",
"schemars 1.2.1",
diff --git a/rust/cloud-storage/agent/Cargo.toml b/rust/cloud-storage/agent/Cargo.toml
index 02244fac94..a40d845f0c 100644
--- a/rust/cloud-storage/agent/Cargo.toml
+++ b/rust/cloud-storage/agent/Cargo.toml
@@ -30,6 +30,7 @@ ai_toolset = { path = "../ai_toolset" }
attachment = { path = "../attachment" }
macro_env_var = { path = "../macro_env_var" }
macro_user_id = { path = "../macro_user_id" }
+prompt = { path = "../prompt" }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
diff --git a/rust/cloud-storage/agent/src/agent_loop.rs b/rust/cloud-storage/agent/src/agent_loop.rs
index a6bb2218c9..e70b0addb7 100644
--- a/rust/cloud-storage/agent/src/agent_loop.rs
+++ b/rust/cloud-storage/agent/src/agent_loop.rs
@@ -1,13 +1,13 @@
/// The main entry point: [`AgentLoop`] and [`Session`].
use crate::error::AgentError;
-use crate::hook::{StreamBridge, ToolRouter};
+use crate::hook::{RegisterFn, StreamBridge, ToolRouter};
use crate::model::AgentModel;
use crate::model::router::{AllModelsRouter, RoutedModel};
use crate::model::types::Model;
use crate::provider_env;
use crate::stream::{ChatCompletionStream, StreamPart};
use crate::tool_adapter::DynToolSetAdapter;
-use ai_toolset::{RequestContext, ToolSet as AiToolSet};
+use ai_toolset::{RequestContext, SearchableTool, ToolLoader, ToolSet as AiToolSet};
use ai_usage::{UsageContext, UsageRecorder};
use futures::StreamExt;
use rig_core::agent::{Agent, MultiTurnStreamItem};
@@ -16,7 +16,9 @@ use rig_core::message::Message;
use rig_core::providers::{anthropic, openai};
use rig_core::streaming::{StreamedAssistantContent, StreamingPrompt};
use rig_core::tool::server::{ToolServer, ToolServerHandle};
-use std::sync::{Arc, RwLock};
+use std::future::Future;
+use std::pin::Pin;
+use std::sync::{Arc, Mutex, RwLock};
const DEFAULT_MAX_TURNS: usize = 16;
const DEFAULT_MAX_TOKENS: u64 = 16_000;
@@ -118,9 +120,26 @@ impl AgentLoop {
where
Context: Clone + Send + Sync + 'static,
{
- let request_context = Arc::new(RwLock::new(RequestContext {
- user_id: usage_ctx.user.clone(),
- }));
+ // On-demand tool search: the toolset's searchable catalog (e.g. MCP
+ // tools) is NOT sent on every request. `SearchTools` reads this catalog
+ // from the request context, matches the model's query, and pushes the
+ // matches into `loaded_buffer` via the loader; the stream bridge then
+ // registers them with the live tool server before the next turn.
+ let catalog = toolset.searchable_catalog();
+ // Names of the connected toolsets (MCP servers) whose tools are
+ // searchable but not advertised upfront. Injected into the system prompt
+ // so the model knows which integrations it can reach via tool search.
+ let searchable_toolset_names = toolset.searchable_toolset_names();
+ let loaded_buffer: Arc<Mutex<Vec<SearchableTool>>> = Arc::new(Mutex::new(Vec::new()));
+ let loader = {
+ let buffer = loaded_buffer.clone();
+ ToolLoader::new(move |tools| {
+ buffer.lock().expect("loaded_buffer poisoned").extend(tools)
+ })
+ };
+ let request_context = Arc::new(RwLock::new(
+ RequestContext::new(usage_ctx.user.clone()).with_tool_search(Arc::new(catalog), loader),
+ ));
// Keep a handle to the toolset so the stream bridge can resolve MCP
// routing info (service / display name) for tool calls. This is the
@@ -129,7 +148,11 @@ impl AgentLoop {
let routing: ToolRouter =
Arc::new(move |name: &str| routing_toolset.routing_description(name));
- let adapters = DynToolSetAdapter::from_toolset(toolset, context, request_context);
+ let adapters = DynToolSetAdapter::from_toolset(
+ toolset.clone(),
+ context.clone(),
+ request_context.clone(),
+ );
let handle = ToolServer::new().run();
for adapter in adapters {
@@ -139,10 +162,63 @@ impl AgentLoop {
.expect("failed to register tool");
}
+ // Registers `SearchTools`-discovered tools with the live tool server so
+ // they become advertised + callable next turn. Context-erased so the
+ // bridge (which is not generic over `Context`) can hold it. Captures
+ // strong refs to the session's shared state but is itself only held by
+ // the bridge/session — nothing the handle owns points back to it, so no
+ // reference cycle.
+ // Names already loaded this session, so repeated searches don't register
+ // a tool twice (which would send a duplicate tool definition and 400).
+ let loaded_names: Arc<Mutex<std::collections::HashSet<String>>> =
+ Arc::new(Mutex::new(std::collections::HashSet::new()));
+ let register_loaded: RegisterFn = {
+ let handle = handle.clone();
+ let toolset = toolset.clone();
+ let context = context.clone();
+ let request_context = request_context.clone();
+ Arc::new(move |tools: Vec<SearchableTool>| {
+ let handle = handle.clone();
+ let toolset = toolset.clone();
+ let context = context.clone();
+ let request_context = request_context.clone();
+ let loaded_names = loaded_names.clone();
+ Box::pin(async move {
+ for tool in tools {
+ // Skip tools already loaded this session.
+ if !loaded_names
+ .lock()
+ .expect("loaded_names poisoned")
+ .insert(tool.name.clone())
+ {
+ continue;
+ }
+ let adapter = DynToolSetAdapter::loaded(
+ tool.name,
+ tool.schema,
+ toolset.clone(),
+ context.clone(),
+ request_context.clone(),
+ );
+ if let Err(e) = handle.add_tool(adapter).await {
+ tracing::warn!(error = ?e, "failed to load searched tool");
+ }
+ }
+ }) as Pin<Box<dyn Future<Output = ()> + Send>>
+ })
+ };
+
// Tell the model which model it is. Done here (not on the frontend)
// so the system prompt always reflects the model actually serving the
// request.
- let system_prompt = format!("{system_prompt}\n\nYou are the {} model.", self.model);
+ let mut system_prompt = format!("{system_prompt}\n\nYou are the {} model.", self.model);
+ // Tell the model which connected integrations it can reach via tool
+ // search. The prompt text lives in the `prompt` crate; the toolset names
+ // are the dynamic data injected here. Omitted when nothing is connected.
+ if let Some(section) = prompt::connected_toolsets::render(&searchable_toolset_names) {
+ system_prompt.push_str("\n\n");
+ system_prompt.push_str(&section);
+ }
// The frontend selects the model by api id; route it to the provider
// that serves it (falling back to the default on unknown / unavailable
@@ -175,6 +251,8 @@ impl AgentLoop {
history: Vec::new(),
max_turns: self.max_turns,
routing,
+ loaded_buffer,
+ register_loaded,
recorder: self.recorder.clone(),
usage_ctx,
model: self.model.clone(),
@@ -194,6 +272,10 @@ pub struct Session {
history: Vec<Message>,
max_turns: usize,
routing: ToolRouter,
+ /// Tools `SearchTools` asked to load, shared with the stream bridge.
+ loaded_buffer: Arc<Mutex<Vec<SearchableTool>>>,
+ /// Registers loaded tools with the live tool server (see [`RegisterFn`]).
+ register_loaded: RegisterFn,
recorder: Arc<dyn UsageRecorder>,
usage_ctx: UsageContext,
model: String,
@@ -225,6 +307,8 @@ impl Session {
history.to_vec(),
self.max_turns,
self.routing.clone(),
+ self.loaded_buffer.clone(),
+ self.register_loaded.clone(),
self.recorder.clone(),
self.usage_ctx.clone(),
self.model.clone(),
@@ -238,6 +322,8 @@ impl Session {
history.to_vec(),
self.max_turns,
self.routing.clone(),
+ self.loaded_buffer.clone(),
+ self.register_loaded.clone(),
self.recorder.clone(),
self.usage_ctx.clone(),
self.model.clone(),
@@ -264,6 +350,8 @@ async fn run_stream<M>(
history: Vec<Message>,
max_turns: usize,
routing: ToolRouter,
+ loaded_buffer: Arc<Mutex<Vec<SearchableTool>>>,
+ register_loaded: RegisterFn,
recorder: Arc<dyn UsageRecorder>,
usage_ctx: UsageContext,
model: String,
@@ -272,7 +360,7 @@ where
M: CompletionModel + 'static,
M::StreamingResponse: GetTokenUsage + Send + Sync,
{
- let (bridge, mut rx) = StreamBridge::channel(routing);
+ let (bridge, mut rx) = StreamBridge::channel(routing, loaded_buffer, register_loaded);
let mut rig_stream = agent
.stream_prompt(prompt)
diff --git a/rust/cloud-storage/agent/src/hook.rs b/rust/cloud-storage/agent/src/hook.rs
index 4433b3c169..56200f4bd4 100644
--- a/rust/cloud-storage/agent/src/hook.rs
+++ b/rust/cloud-storage/agent/src/hook.rs
@@ -1,12 +1,17 @@
/// A [`rig_core::agent::PromptHook`] that bridges RIG lifecycle events into
/// [`StreamPart`] items sent through a channel.
+#[cfg(test)]
+mod test;
+
use crate::AgentError;
use crate::stream::{McpInfo, StreamPart, ToolCall, ToolResponse, Usage};
-use ai_toolset::ToolInfo;
+use ai_toolset::{SearchableTool, ToolInfo};
use rig_core::agent::{HookAction, PromptHook, ToolCallHookAction};
use rig_core::completion::{CompletionModel, GetTokenUsage};
use rig_core::message::Message;
-use std::sync::Arc;
+use std::future::Future;
+use std::pin::Pin;
+use std::sync::{Arc, Mutex};
use tokio::sync::mpsc;
/// Resolves a tool name to its routing [`ToolInfo`] via the session's toolset.
@@ -17,27 +22,53 @@ use tokio::sync::mpsc;
/// name, and display name. Returns `None` for native tools.
pub type ToolRouter = Arc<dyn Fn(&str) -> Option<ToolInfo> + Send + Sync>;
+/// Registers tools loaded on demand (via `SearchTools`) with the live tool
+/// server so they are advertised and callable on the next turn.
+///
+/// Built by the agent layer (which captures the tool-server handle and the
+/// session's context); context-erased so the bridge stays generic-free.
+pub type RegisterFn =
+ Arc<dyn Fn(Vec<SearchableTool>) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync>;
+
/// Sends [`StreamPart`] items through an unbounded channel as the RIG agentic
/// loop produces events.
#[derive(Clone)]
pub struct StreamBridge {
tx: mpsc::UnboundedSender<Result<StreamPart, AgentError>>,
routing: ToolRouter,
+ /// Tools the `SearchTools` tool asked to load this turn, awaiting
+ /// registration. Drained in [`Self::on_tool_result`].
+ loaded_buffer: Arc<Mutex<Vec<SearchableTool>>>,
+ /// Registers drained tools with the live tool server.
+ register_loaded: RegisterFn,
}
impl StreamBridge {
/// Create a bridge and its receiving half.
///
/// `routing` resolves tool names to [`ToolInfo`] so MCP calls can be
- /// tagged as such (see [`ToolRouter`]).
+ /// tagged as such (see [`ToolRouter`]). `loaded_buffer` / `register_loaded`
+ /// power on-demand tool loading: `SearchTools` pushes matches into the
+ /// buffer, and the bridge registers them after the tool result, before the
+ /// next turn (see [`Self::on_tool_result`]).
pub fn channel(
routing: ToolRouter,
+ loaded_buffer: Arc<Mutex<Vec<SearchableTool>>>,
+ register_loaded: RegisterFn,
) -> (
Self,
mpsc::UnboundedReceiver<Result<StreamPart, AgentError>>,
) {
let (tx, rx) = mpsc::unbounded_channel();
- (Self { tx, routing }, rx)
+ (
+ Self {
+ tx,
+ routing,
+ loaded_buffer,
+ register_loaded,
+ },
+ rx,
+ )
}
}
@@ -88,6 +119,18 @@ where
_args: &str,
result: &str,
) -> HookAction {
+ // Register any tools `SearchTools` asked to load. This fires after the
+ // tool executes and before the next turn's request is built, so loaded
+ // tools are advertised + callable next turn. (The lock guard is dropped
+ // before the await.)
+ let pending: Vec<SearchableTool> = {
+ let mut buf = self.loaded_buffer.lock().expect("loaded_buffer poisoned");
+ std::mem::take(&mut *buf)
+ };
+ if !pending.is_empty() {
+ (self.register_loaded)(pending).await;
+ }
+
let id = tool_call_id.unwrap_or_else(|| internal_call_id.to_owned());
let response = match serde_json::from_str::<serde_json::Value>(result) {
Ok(json) => ToolResponse::Json {
diff --git a/rust/cloud-storage/agent/src/hook/test.rs b/rust/cloud-storage/agent/src/hook/test.rs
new file mode 100644
index 0000000000..7c8eedb253
--- /dev/null
+++ b/rust/cloud-storage/agent/src/hook/test.rs
@@ -0,0 +1,81 @@
+use super::*;
+use rig_core::providers::anthropic::completion::CompletionModel as AnthropicModel;
+use schemars::Schema;
+use std::sync::Mutex;
+
+fn searchable(name: &str) -> SearchableTool {
+ SearchableTool {
+ name: name.to_string(),
+ description: "desc".to_string(),
+ schema: Schema::default(),
+ }
+}
+
+/// A register fn that records the names it was handed.
+fn recording_register() -> (RegisterFn, Arc<Mutex<Vec<String>>>) {
+ let recorded = Arc::new(Mutex::new(Vec::<String>::new()));
+ let sink = recorded.clone();
+ let register: RegisterFn = Arc::new(move |tools: Vec<SearchableTool>| {
+ let sink = sink.clone();
+ Box::pin(async move {
+ sink.lock()
+ .unwrap()
+ .extend(tools.into_iter().map(|t| t.name));
+ }) as Pin<Box<dyn Future<Output = ()> + Send>>
+ });
+ (register, recorded)
+}
+
+#[tokio::test]
+async fn on_tool_result_drains_buffer_and_registers_loaded_tools() {
+ let buffer = Arc::new(Mutex::new(vec![
+ searchable("mcp__slack__send"),
+ searchable("mcp__linear__create_issue"),
+ ]));
+ let (register, registered) = recording_register();
+ let routing: ToolRouter = Arc::new(|_| None);
+ let (bridge, _rx) = StreamBridge::channel(routing, buffer.clone(), register);
+
+ let action = <StreamBridge as PromptHook<AnthropicModel>>::on_tool_result(
+ &bridge,
+ "SearchTools",
+ None,
+ "call-1",
+ "{}",
+ "{\"loaded\":[]}",
+ )
+ .await;
+
+ assert!(matches!(action, HookAction::Continue));
+ // Buffer drained and both pending tools handed to the registrar.
+ assert!(buffer.lock().unwrap().is_empty());
+ let mut got = registered.lock().unwrap().clone();
+ got.sort();
+ assert_eq!(
+ got,
+ vec![
+ "mcp__linear__create_issue".to_string(),
+ "mcp__slack__send".to_string()
+ ]
+ );
+}
+
+#[tokio::test]
+async fn on_tool_result_registers_nothing_when_buffer_empty() {
+ let buffer = Arc::new(Mutex::new(Vec::new()));
+ let (register, registered) = recording_register();
+ let routing: ToolRouter = Arc::new(|_| None);
+ let (bridge, _rx) = StreamBridge::channel(routing, buffer, register);
+
+ let _ = <StreamBridge as PromptHook<AnthropicModel>>::on_tool_result(
+ &bridge,
+ "WebSearch",
+ None,
+ "call-2",
+ "{}",
+ "{}",
+ )
+ .await;
+
+ assert!(registered.lock().unwrap().is_empty());
+}
diff --git a/rust/cloud-storage/agent/src/tool_adapter.rs b/rust/cloud-storage/agent/src/tool_adapter.rs
index 863048081c..28a191d9cb 100644
--- a/rust/cloud-storage/agent/src/tool_adapter.rs
+++ b/rust/cloud-storage/agent/src/tool_adapter.rs
@@ -202,6 +202,31 @@ where
})
.collect()
}
+
+ /// Build a single adapter for a tool loaded on demand via tool search.
+ ///
+ /// Used to register a `SearchTools`-discovered tool with the live tool
+ /// server mid-session so it becomes advertised and callable on the next
+ /// turn. Calls dispatch through the shared `toolset` by name, exactly like
+ /// [`Self::from_toolset`].
+ pub fn loaded(
+ name: String,
+ schema: schemars::Schema,
+ toolset: Arc<dyn AiToolSet<Context> + Send + Sync>,
+ context: Arc<Context>,
+ request_context: Arc<RwLock<RequestContext>>,
+ ) -> Self {
+ let mut schema_json = serde_json::to_value(&schema)
+ .unwrap_or(serde_json::Value::Object(serde_json::Map::new()));
+ normalize_request_schema(&mut schema_json);
+ DynToolSetAdapter {
+ name,
+ schema: schema_json,
+ toolset,
+ context,
+ request_context,
+ }
+ }
}
unsafe impl<C: Send + Sync> Send for DynToolSetAdapter<C> {}
diff --git a/rust/cloud-storage/ai_tools/src/lib.rs b/rust/cloud-storage/ai_tools/src/lib.rs
index 29e1b2ffbc..f8af474707 100644
--- a/rust/cloud-storage/ai_tools/src/lib.rs
+++ b/rust/cloud-storage/ai_tools/src/lib.rs
@@ -6,6 +6,7 @@ mod build_context;
mod display_results;
mod schemas;
pub mod search;
+mod search_tools;
pub mod serde_utils;
mod subagent;
mod tool_context;
@@ -21,6 +22,7 @@ use email::inbound::toolset::{email_toolset, mcp_toolset as email_mcp_toolset};
use notification::inbound::ai_tool::notification_toolset;
use properties::inbound::toolset::properties_toolset;
use schemas::read;
+use search_tools::{LoadTools, SearchTools};
use soup::inbound::toolset::{ListEntities, SoupToolContext};
use std::sync::Arc;
use subagent::Subagent;
@@ -83,6 +85,8 @@ pub fn all_tools() -> ToolSetWithPrompt {
.add_subtoolset::<ToolNotificationToolContext>(notification_toolset())
.add_subtoolset::<ToolEmailToolContext>(email_toolset())
.add_tool::<Subagent, ToolServiceContext>()
+ .add_tool::<SearchTools, ToolServiceContext>()
+ .add_tool::<LoadTools, ToolServiceContext>()
.add_tool::<DisplayResults, ToolServiceContext>();
let toolset = Arc::new(toolset);
ToolSetWithPrompt {
diff --git a/rust/cloud-storage/ai_tools/src/search_tools.rs b/rust/cloud-storage/ai_tools/src/search_tools.rs
new file mode 100644
index 0000000000..06af7b941b
--- /dev/null
+++ b/rust/cloud-storage/ai_tools/src/search_tools.rs
@@ -0,0 +1,190 @@
+use ai_toolset::{
+ AsyncTool, RequestContext, SearchableTool, ServiceContext, ToolLoader, ToolResult,
+};
+use async_trait::async_trait;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+use crate::ToolServiceContext;
+
+#[cfg(test)]
+mod test;
+
+/// A tool surfaced by [`SearchTools`] or loaded by [`LoadTools`] — just enough
+/// for the model to decide whether to load it and how to call it.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct ToolMatch {
+ /// The exact name to load and then call the tool by.
+ pub name: String,
+ /// What the tool does.
+ pub description: String,
+}
+
+// ---------------------------------------------------------------------------
+// SearchTools — discovery only
+// ---------------------------------------------------------------------------
+
+/// Response from [`SearchTools`]: matching tools (name + description), not yet
+/// loaded.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct SearchToolsResponse {
+ /// Tools matching the query. Call `LoadTools` with the names you want to use.
+ pub results: Vec<ToolMatch>,
+}
+
+/// `SearchTools` discovers tools from connected integrations (MCP servers such
+/// as Slack, Gmail, Linear) that are not listed upfront. It only *finds* tools —
+/// returning their names and descriptions — without loading them, so it can
+/// return many candidates cheaply. To actually use a tool, pass its name to
+/// `LoadTools`.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(
+ title = "SearchTools",
+ description = "Find tools from connected integrations (e.g. Slack, Gmail, Linear, GitHub) by keyword. Returns matching tools' names and descriptions but does NOT load them — pass the names you want to `LoadTools` to make them callable. Searching is cheap, so cast a wide net."
+)]
+pub struct SearchTools {
+ /// Keywords describing the capability you need (matched against tool names
+ /// and descriptions, case-insensitive).
+ #[schemars(
+ description = "Keywords describing the capability you need, e.g. \"linear issue\" or \"github list commits\"."
+ )]
+ pub query: String,
+}
+
+#[async_trait]
+impl AsyncTool<ToolServiceContext> for SearchTools {
+ type Output = SearchToolsResponse;
+
+ #[tracing::instrument(skip_all, fields(query = %self.query), err)]
+ async fn call(
+ &self,
+ _service_context: ServiceContext<ToolServiceContext>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ Ok(SearchToolsResponse {
+ results: search(&request_context.searchable_tools, &self.query),
+ })
+ }
+}
+
+// ---------------------------------------------------------------------------
+// LoadTools — load named tools so they become callable
+// ---------------------------------------------------------------------------
+
+/// Response from [`LoadTools`]: which requested tools were loaded, and any names
+/// that weren't found.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct LoadToolsResponse {
+ /// Tools that are now loaded and callable by name.
+ pub loaded: Vec<ToolMatch>,
+ /// Requested names that don't exist (call `SearchTools` to find valid names).
+ pub not_found: Vec<String>,
+}
+
+/// `LoadTools` loads tools discovered via `SearchTools` so they become callable.
+/// Pass the exact names from the search results; after loading, call each tool
+/// by its name as usual.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(
+ title = "LoadTools",
+ description = "Load tools by name (from `SearchTools` results) so you can call them. After loading, invoke each tool by its name. Only load the tools you actually need."
+)]
+pub struct LoadTools {
+ /// Exact tool names to load, as returned by `SearchTools`.
+ #[schemars(description = "Exact tool names to load, taken from SearchTools results.")]
+ pub names: Vec<String>,
+}
+
+#[async_trait]
+impl AsyncTool<ToolServiceContext> for LoadTools {
+ type Output = LoadToolsResponse;
+
+ #[tracing::instrument(skip_all, fields(names = ?self.names), err)]
+ async fn call(
+ &self,
+ _service_context: ServiceContext<ToolServiceContext>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ Ok(load(
+ &request_context.searchable_tools,
+ &self.names,
+ request_context.tool_loader.as_ref(),
+ ))
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Pure logic (unit-testable without a service context)
+// ---------------------------------------------------------------------------
+
+/// Match `query` against `catalog` and return the matches' name + description,
+/// ranked by relevance. Does not load anything.
+///
+/// The query is split into whitespace-separated terms; a tool matches if **any**
+/// term is a case-insensitive substring of its name or description, ranked by
+/// how many distinct terms match (so "github list commits" surfaces the most
+/// relevant tools first). All matches are returned — searching is cheap and
+/// loading is a separate step. An empty query returns the whole catalog.
+fn search(catalog: &[SearchableTool], query: &str) -> Vec<ToolMatch> {
+ let query = query.to_lowercase();
+ let terms: Vec<&str> = query.split_whitespace().collect();
+
+ let mut scored: Vec<(usize, &SearchableTool)> = catalog
+ .iter()
+ .filter_map(|t| {
+ if terms.is_empty() {
+ return Some((0, t));
+ }
+ let haystack = format!("{} {}", t.name.to_lowercase(), t.description.to_lowercase());
+ let score = terms
+ .iter()
+ .filter(|term| haystack.contains(**term))
+ .count();
+ (score > 0).then_some((score, t))
+ })
+ .collect();
+ // Highest term-match count first; tie-break by name for stable ordering.
+ scored.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.name.cmp(&b.1.name)));
+
+ scored
+ .into_iter()
+ .map(|(_, t)| ToolMatch {
+ name: t.name.clone(),
+ description: t.description.clone(),
+ })
+ .collect()
+}
+
+/// Look up `names` in `catalog`, hand the found tools to `loader` for loading,
+/// and report which were loaded vs not found.
+fn load(
+ catalog: &[SearchableTool],
+ names: &[String],
+ loader: Option<&ToolLoader>,
+) -> LoadToolsResponse {
+ let mut to_load = Vec::new();
+ let mut loaded = Vec::new();
+ let mut not_found = Vec::new();
+ for name in names {
+ match catalog.iter().find(|t| &t.name == name) {
+ Some(t) => {
+ loaded.push(ToolMatch {
+ name: t.name.clone(),
+ description: t.description.clone(),
+ });
+ to_load.push(t.clone());
+ }
+ None => not_found.push(name.clone()),
+ }
+ }
+
+ // Hand the found tools to the loader; the agent layer registers them with
+ // the live tool server so they are callable on the next turn.
+ if !to_load.is_empty()
+ && let Some(loader) = loader
+ {
+ loader.load(to_load);
+ }
+
+ LoadToolsResponse { loaded, not_found }
+}
diff --git a/rust/cloud-storage/ai_tools/src/search_tools/test.rs b/rust/cloud-storage/ai_tools/src/search_tools/test.rs
new file mode 100644
index 0000000000..1de07c145f
--- /dev/null
+++ b/rust/cloud-storage/ai_tools/src/search_tools/test.rs
@@ -0,0 +1,124 @@
+use super::*;
+use ai_toolset::ToolLoader;
+use schemars::Schema;
+use std::sync::{Arc, Mutex};
+
+fn tool(name: &str, description: &str) -> SearchableTool {
+ SearchableTool {
+ name: name.to_string(),
+ description: description.to_string(),
+ schema: Schema::default(),
+ }
+}
+
+fn catalog() -> Vec<SearchableTool> {
+ vec![
+ tool(
+ "mcp__slack__send_message",
+ "Post a message to a Slack channel",
+ ),
+ tool("mcp__gmail__list_threads", "List email threads in Gmail"),
+ tool("mcp__linear__create_issue", "Create a Linear issue"),
+ ]
+}
+
+/// A loader that records the names of tools it was asked to load.
+fn recording_loader() -> (ToolLoader, Arc<Mutex<Vec<String>>>) {
+ let recorded = Arc::new(Mutex::new(Vec::new()));
+ let sink = recorded.clone();
+ let loader = ToolLoader::new(move |tools| {
+ sink.lock()
+ .unwrap()
+ .extend(tools.into_iter().map(|t| t.name));
+ });
+ (loader, recorded)
+}
+
+fn names(matches: &[ToolMatch]) -> Vec<&str> {
+ matches.iter().map(|m| m.name.as_str()).collect()
+}
+
+// --- search (discovery only, never loads) ---
+
+#[test]
+fn search_matches_by_name() {
+ let results = search(&catalog(), "linear");
+ assert_eq!(names(&results), vec!["mcp__linear__create_issue"]);
+}
+
+#[test]
+fn search_matches_by_description_case_insensitive() {
+ // "EMAIL" matches the Gmail tool's description ("email threads").
+ let results = search(&catalog(), "EMAIL");
+ assert_eq!(names(&results), vec!["mcp__gmail__list_threads"]);
+}
+
+#[test]
+fn search_no_match_returns_empty() {
+ assert!(search(&catalog(), "notion").is_empty());
+}
+
+#[test]
+fn search_empty_query_returns_all() {
+ assert_eq!(search(&catalog(), "").len(), 3);
+}
+
+#[test]
+fn search_multi_word_matches_any_term_and_ranks_by_term_count() {
+ // "slack" + "message" both hit the Slack tool (score 2); "linear" hits the
+ // Linear tool (score 1); Gmail matches none.
+ let results = search(&catalog(), "slack message linear");
+ assert_eq!(
+ names(&results),
+ vec!["mcp__slack__send_message", "mcp__linear__create_issue"]
+ );
+}
+
+#[test]
+fn search_is_uncapped() {
+ let big: Vec<SearchableTool> = (0..50)
+ .map(|i| tool(&format!("mcp__svc__tool_{i:02}"), "a tool"))
+ .collect();
+ assert_eq!(search(&big, "tool").len(), 50);
+}
+
+// --- load (registers named tools via the loader) ---
+
+#[test]
+fn load_loads_named_tools_and_reports_them() {
+ let (loader, loaded) = recording_loader();
+ let result = load(
+ &catalog(),
+ &["mcp__linear__create_issue".to_string()],
+ Some(&loader),
+ );
+
+ assert_eq!(names(&result.loaded), vec!["mcp__linear__create_issue"]);
+ assert!(result.not_found.is_empty());
+ // The found tool was handed to the loader for registration.
+ assert_eq!(&*loaded.lock().unwrap(), &["mcp__linear__create_issue"]);
+}
+
+#[test]
+fn load_reports_unknown_names_and_loads_the_rest() {
+ let (loader, loaded) = recording_loader();
+ let result = load(
+ &catalog(),
+ &[
+ "mcp__slack__send_message".to_string(),
+ "mcp__nope__missing".to_string(),
+ ],
+ Some(&loader),
+ );
+
+ assert_eq!(names(&result.loaded), vec!["mcp__slack__send_message"]);
+ assert_eq!(result.not_found, vec!["mcp__nope__missing".to_string()]);
+ assert_eq!(&*loaded.lock().unwrap(), &["mcp__slack__send_message"]);
+}
+
+#[test]
+fn load_without_loader_still_reports() {
+ let result = load(&catalog(), &["mcp__gmail__list_threads".to_string()], None);
+ assert_eq!(names(&result.loaded), vec!["mcp__gmail__list_threads"]);
+ assert!(result.not_found.is_empty());
+}
diff --git a/rust/cloud-storage/ai_toolset/src/context.rs b/rust/cloud-storage/ai_toolset/src/context.rs
index 19809d3030..19eaffee40 100644
--- a/rust/cloud-storage/ai_toolset/src/context.rs
+++ b/rust/cloud-storage/ai_toolset/src/context.rs
@@ -1,5 +1,7 @@
+use crate::tool_search::{SearchableTool, ToolLoader};
use macro_user_id::user_id::MacroUserIdStr;
use std::ops::{Deref, DerefMut};
+use std::sync::Arc;
/// Service context wrapper for shared state passed to tools.
///
@@ -27,4 +29,34 @@ impl<S> DerefMut for ServiceContext<S> {
pub struct RequestContext {
/// The ID of the user making the request.
pub user_id: MacroUserIdStr<'static>,
+ /// Catalog of on-demand (searchable) tools for this request, read by the
+ /// `SearchTools` tool to match the model's query. Empty when the request has
+ /// no searchable tools.
+ pub searchable_tools: Arc<Vec<SearchableTool>>,
+ /// Loader used by `SearchTools` to load matched tools into the active
+ /// request. `None` when tool search is not wired up (e.g. non-agent callers).
+ pub tool_loader: Option<ToolLoader>,
+}
+
+impl RequestContext {
+ /// Create a request context for `user_id` with no tool-search wiring (no
+ /// searchable catalog, no loader).
+ pub fn new(user_id: MacroUserIdStr<'static>) -> Self {
+ Self {
+ user_id,
+ searchable_tools: Arc::new(Vec::new()),
+ tool_loader: None,
+ }
+ }
+
+ /// Attach the searchable-tool catalog and loader that power `SearchTools`.
+ pub fn with_tool_search(
+ mut self,
+ searchable_tools: Arc<Vec<SearchableTool>>,
+ tool_loader: ToolLoader,
+ ) -> Self {
+ self.searchable_tools = searchable_tools;
+ self.tool_loader = Some(tool_loader);
+ self
+ }
}
diff --git a/rust/cloud-storage/ai_toolset/src/lib.rs b/rust/cloud-storage/ai_toolset/src/lib.rs
index 91879fc88b..eacce58098 100644
--- a/rust/cloud-storage/ai_toolset/src/lib.rs
+++ b/rust/cloud-storage/ai_toolset/src/lib.rs
@@ -19,7 +19,7 @@
//! ensures compile-time safety when extracting tool-specific contexts.
//!
//! ```
-//! use ai_toolset::{AsyncTool, AsyncToolSet, RequestContext, ServiceContext, ToolResult};
+//! use ai_toolset::{AsyncTool, AsyncToolCollection, RequestContext, ServiceContext, ToolResult};
//! use axum_macros::FromRef;
//! use schemars::JsonSchema;
//! use serde::{Deserialize, Serialize};
@@ -72,7 +72,7 @@
//! }
//!
//! // Build toolset with tools using different contexts
-//! let toolset = AsyncToolSet::<AppContext>::new()
+//! let toolset = AsyncToolCollection::<AppContext>::new()
//! .add_tool::<ReadDocumentTool, Arc<dyn DocumentApi>>()
//! .add_tool::<UpdatePropertyTool, Arc<dyn PropertyApi>>();
//! ```
@@ -84,7 +84,7 @@
//! derivable from the parent context via `FromRef`.
//!
//! ```
-//! use ai_toolset::{AsyncTool, AsyncToolSet, RequestContext, ServiceContext, ToolResult};
+//! use ai_toolset::{AsyncTool, AsyncToolCollection, RequestContext, ServiceContext, ToolResult};
//! use axum_macros::FromRef;
//! use schemars::JsonSchema;
//! use serde::{Deserialize, Serialize};
@@ -117,11 +117,11 @@
//! }
//!
//! // Build a subtoolset with the narrower context
-//! let sub_toolset = AsyncToolSet::<SubContext>::new()
+//! let sub_toolset = AsyncToolCollection::<SubContext>::new()
//! .add_tool::<SubTool, SubContext>();
//!
//! // Merge into parent toolset - tools are automatically widened
-//! let parent_toolset = AsyncToolSet::<ParentContext>::new()
+//! let parent_toolset = AsyncToolCollection::<ParentContext>::new()
//! .add_subtoolset::<SubContext>(sub_toolset);
//!
//! assert!(parent_toolset.tools.contains_key("SubTool"));
@@ -132,10 +132,12 @@
mod context;
pub mod schema;
mod tool;
+pub mod tool_search;
mod toolset;
pub use context::{RequestContext, ServiceContext};
pub use tool::{AsyncTool, NoContext, ToolCallError, ToolResult};
+pub use tool_search::{SearchableTool, ToolLoader};
pub use toolset::{
AsyncToolCollection, RequestSchema, ToolCollection, ToolInfo, ToolSchema, ToolSet,
ToolSetCreationError, ToolSetError, tool_object,
diff --git a/rust/cloud-storage/ai_toolset/src/tool_search.rs b/rust/cloud-storage/ai_toolset/src/tool_search.rs
new file mode 100644
index 0000000000..cea7befe1a
--- /dev/null
+++ b/rust/cloud-storage/ai_toolset/src/tool_search.rs
@@ -0,0 +1,107 @@
+//! Primitives for custom (provider-agnostic) tool search.
+//!
+//! A toolset can mark some tools as **searchable** (loaded on demand) rather
+//! than sent on every request. The catalog of those tools is exposed via
+//! [`ToolSet::searchable_catalog`](crate::ToolSet::searchable_catalog). A
+//! first-party `SearchTools` tool reads the catalog from the
+//! [`RequestContext`](crate::RequestContext), matches the model's query, and
+//! asks the [`ToolLoader`] to load the matches — the agent layer's loader makes
+//! them real, callable tools on the next turn. This keeps a large/growing tool
+//! catalog out of every request without depending on any provider's native
+//! tool-search feature.
+
+use schemars::Schema;
+use std::sync::Arc;
+
+/// A tool that is loaded on demand via tool search rather than sent on every
+/// request. The catalog of these is returned by
+/// [`ToolSet::searchable_catalog`](crate::ToolSet::searchable_catalog) and read
+/// by the `SearchTools` tool to match the model's query.
+#[derive(Clone, Debug)]
+pub struct SearchableTool {
+ /// The tool's name, exactly as it must be called (e.g. a mangled MCP name).
+ pub name: String,
+ /// Human-readable description, matched against search queries.
+ pub description: String,
+ /// JSON schema for the tool's input — needed to register the tool once it
+ /// is loaded.
+ pub schema: Schema,
+}
+
+/// Callback that loads searchable tools into the active request.
+///
+/// `SearchTools` calls this with the tools matching the query. The agent layer
+/// supplies the implementation, which registers the tools with the live tool
+/// server so they become advertised and callable on the next turn. Defined here
+/// as a plain `Fn` so `ai_toolset` stays free of any agent/rig dependency.
+#[derive(Clone)]
+pub struct ToolLoader(Arc<dyn Fn(Vec<SearchableTool>) + Send + Sync>);
+
+impl ToolLoader {
+ /// Wrap a closure as a [`ToolLoader`].
+ pub fn new(f: impl Fn(Vec<SearchableTool>) + Send + Sync + 'static) -> Self {
+ Self(Arc::new(f))
+ }
+
+ /// Request that `tools` be loaded into the active request.
+ pub fn load(&self, tools: Vec<SearchableTool>) {
+ (self.0)(tools)
+ }
+}
+
+impl std::fmt::Debug for ToolLoader {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str("ToolLoader")
+ }
+}
+
+#[cfg(test)]
+mod test {
+ use super::*;
+ use crate::RequestContext;
+ use macro_user_id::user_id::MacroUserIdStr;
+ use std::sync::Mutex;
+
+ fn tool(name: &str) -> SearchableTool {
+ SearchableTool {
+ name: name.to_string(),
+ description: String::new(),
+ schema: Schema::default(),
+ }
+ }
+
+ #[test]
+ fn tool_loader_forwards_to_its_closure() {
+ let seen = Arc::new(Mutex::new(Vec::<String>::new()));
+ let sink = seen.clone();
+ let loader = ToolLoader::new(move |tools| {
+ sink.lock()
+ .unwrap()
+ .extend(tools.into_iter().map(|t| t.name));
+ });
+
+ loader.load(vec![tool("a"), tool("b")]);
+
+ assert_eq!(&*seen.lock().unwrap(), &["a".to_string(), "b".to_string()]);
+ }
+
+ #[test]
+ fn request_context_new_has_no_tool_search() {
+ let user = MacroUserIdStr::try_from_email("[email protected]").unwrap();
+ let ctx = RequestContext::new(user);
+ assert!(ctx.searchable_tools.is_empty());
+ assert!(ctx.tool_loader.is_none());
+ }
+
+ #[test]
+ fn with_tool_search_wires_catalog_and_loader() {
+ let user = MacroUserIdStr::try_from_email("[email protected]").unwrap();
+ let catalog = Arc::new(vec![tool("mcp__x__y")]);
+ let loader = ToolLoader::new(|_| {});
+ let ctx = RequestContext::new(user).with_tool_search(catalog, loader);
+
+ assert_eq!(ctx.searchable_tools.len(), 1);
+ assert_eq!(ctx.searchable_tools[0].name, "mcp__x__y");
+ assert!(ctx.tool_loader.is_some());
+ }
+}
diff --git a/rust/cloud-storage/ai_toolset/src/toolset/traits.rs b/rust/cloud-storage/ai_toolset/src/toolset/traits.rs
index 15d6878bd1..fb84991cb2 100644
--- a/rust/cloud-storage/ai_toolset/src/toolset/traits.rs
+++ b/rust/cloud-storage/ai_toolset/src/toolset/traits.rs
@@ -1,6 +1,6 @@
//! The core ToolSet trait implemented by the ToolSet and AsyncToolset
use crate::toolset::types::{RequestSchema, ToolInfo};
-use crate::{AsyncToolCollection, RequestContext, ToolResult, ToolSetError};
+use crate::{AsyncToolCollection, RequestContext, SearchableTool, ToolResult, ToolSetError};
use std::pin::Pin;
/// An object with a set of tools
@@ -16,9 +16,25 @@ pub trait ToolSet<Context>: Send + Sync {
Box<dyn Future<Output = Result<ToolResult<serde_json::Value>, ToolSetError>> + 'a + Send>,
>;
- /// Returns the input schemas for all tools in the toolset, or `None` if the toolset is empty.
+ /// Returns the input schemas for the tools sent to the provider on every
+ /// request. Tools loaded on demand via tool search are excluded — they are
+ /// surfaced through [`Self::searchable_catalog`] instead.
fn request_schemas(&self) -> Option<Vec<RequestSchema>>;
+ /// The catalog of on-demand (searchable) tools — those not sent on every
+ /// request but discoverable via the `SearchTools` tool. Defaults to empty.
+ fn searchable_catalog(&self) -> Vec<SearchableTool> {
+ Vec::new()
+ }
+
+ /// Names of the toolsets (e.g. connected MCP servers) whose tools are
+ /// available via tool search but not advertised on every request. Used to
+ /// tell the model which integrations it can reach via `SearchTools` /
+ /// `LoadTools`. Defaults to empty (no searchable toolsets).
+ fn searchable_toolset_names(&self) -> Vec<String> {
+ Vec::new()
+ }
+
/// Dynamic routers use this to demangle tool names for frontend consumption
fn routing_description<'a>(&'a self, _tool_name: &'a str) -> Option<ToolInfo> {
None
diff --git a/rust/cloud-storage/ai_toolset/src/toolset/types.rs b/rust/cloud-storage/ai_toolset/src/toolset/types.rs
index 98a5b2f8d6..b93e48138c 100644
--- a/rust/cloud-storage/ai_toolset/src/toolset/types.rs
+++ b/rust/cloud-storage/ai_toolset/src/toolset/types.rs
@@ -249,7 +249,7 @@ where
/// # Example
///
/// ```
- /// use ai_toolset::{AsyncTool, AsyncToolSet, RequestContext, ServiceContext, ToolResult};
+ /// use ai_toolset::{AsyncTool, AsyncToolCollection, RequestContext, ServiceContext, ToolResult};
/// use axum_macros::FromRef;
/// use schemars::JsonSchema;
/// use serde::{Deserialize, Serialize};
@@ -282,11 +282,11 @@ where
/// }
///
/// // Build a subtoolset with the narrower context
- /// let sub_toolset = AsyncToolSet::<SubContext>::new()
+ /// let sub_toolset = AsyncToolCollection::<SubContext>::new()
/// .add_tool::<SubTool, SubContext>();
///
/// // Merge into parent toolset - tools are automatically widened
- /// let parent_toolset = AsyncToolSet::<ParentContext>::new()
+ /// let parent_toolset = AsyncToolCollection::<ParentContext>::new()
/// .add_subtoolset::<SubContext>(sub_toolset);
///
/// assert!(parent_toolset.tools.contains_key("SubTool"));
diff --git a/rust/cloud-storage/chat/src/domain/service/chat.rs b/rust/cloud-storage/chat/src/domain/service/chat.rs
index 59f41d4e0f..28f2ab525b 100644
--- a/rust/cloud-storage/chat/src/domain/service/chat.rs
+++ b/rust/cloud-storage/chat/src/domain/service/chat.rs
@@ -367,7 +367,7 @@ where
None => stored_args.clone(),
};
- let request_context = RequestContext { user_id };
+ let request_context = RequestContext::new(user_id);
let outcome = self
.toolset
diff --git a/rust/cloud-storage/mcp_client/src/domain/service/toolset.rs b/rust/cloud-storage/mcp_client/src/domain/service/toolset.rs
index 0821aabc74..2863d8956c 100644
--- a/rust/cloud-storage/mcp_client/src/domain/service/toolset.rs
+++ b/rust/cloud-storage/mcp_client/src/domain/service/toolset.rs
@@ -1,8 +1,8 @@
use crate::domain::models::{Error, McpServer, McpServerRecord};
use crate::domain::ports::McpConnector;
use ai_toolset::{
- AsyncToolCollection, RequestContext, RequestSchema, ToolCallError, ToolInfo, ToolResult,
- ToolSet, ToolSetError,
+ AsyncToolCollection, RequestContext, RequestSchema, SearchableTool, ToolCallError, ToolInfo,
+ ToolResult, ToolSet, ToolSetError,
};
use rmcp::RoleClient;
use rmcp::model::{CallToolRequestParams, CallToolResult, Tool};
@@ -119,6 +119,39 @@ impl McpToolSet {
self.tools.is_empty()
}
+ /// The full catalog of MCP tools (mangled name + description + input schema)
+ /// for on-demand loading via tool search.
+ fn catalog(&self) -> Vec<SearchableTool> {
+ self.tools
+ .iter()
+ .map(|(mangled, entry)| SearchableTool {
+ name: mangled.as_str().to_string(),
+ description: entry
+ .tool
+ .description
+ .as_deref()
+ .unwrap_or_default()
+ .to_string(),
+ schema: Schema::from((*entry.tool.input_schema).clone()),
+ })
+ .collect()
+ }
+
+ /// Distinct names of the connected MCP servers that contributed tools,
+ /// sorted for a stable prompt. Derived from the mangled tool keys so it
+ /// reflects the servers actually serving searchable tools this request.
+ fn toolset_names(&self) -> Vec<String> {
+ let mut names: Vec<String> = self
+ .tools
+ .keys()
+ .filter_map(|mangled| MangledName::parse(mangled.as_str()))
+ .map(|(server, _tool)| server.to_string())
+ .collect();
+ names.sort();
+ names.dedup();
+ names
+ }
+
#[tracing::instrument(skip(self, arguments), err)]
async fn call_tool(
&self,
@@ -206,6 +239,10 @@ impl<Context: Send + Sync + 'static> ToolSet<Context> for McpToolSet {
}
}
+ fn searchable_toolset_names(&self) -> Vec<String> {
+ self.toolset_names()
+ }
+
fn routing_description<'a>(&'a self, tool_name: &'a str) -> Option<ToolInfo> {
let (server_name, original_name) = MangledName::parse(tool_name)?;
let key = MangledName(tool_name.to_owned());
@@ -262,15 +299,19 @@ impl<T: Send + Sync + 'static> ToolSet<T> for CombinedToolSet<T> {
}
fn request_schemas(&self) -> Option<Vec<RequestSchema>> {
- let mut schemas = self.static_tools.request_schemas().unwrap_or_default();
- schemas.extend(
- <McpToolSet as ToolSet<T>>::request_schemas(&self.mcp_tools).unwrap_or_default(),
- );
- if schemas.is_empty() {
- None
- } else {
- Some(schemas)
- }
+ // Only the static (first-party) tools are sent on every request. MCP
+ // tools are loaded on demand via the `SearchTools` tool — they are
+ // surfaced through `searchable_catalog`, not here — so a large/growing
+ // MCP catalog never bloats the request.
+ self.static_tools.request_schemas()
+ }
+
+ fn searchable_catalog(&self) -> Vec<SearchableTool> {
+ self.mcp_tools.catalog()
+ }
+
+ fn searchable_toolset_names(&self) -> Vec<String> {
+ self.mcp_tools.toolset_names()
}
fn routing_description<'a>(&'a self, tool_name: &'a str) -> Option<ToolInfo> {
diff --git a/rust/cloud-storage/mcp_service/src/tool_service.rs b/rust/cloud-storage/mcp_service/src/tool_service.rs
index 9e79c37890..12ffa9bbfe 100644
--- a/rust/cloud-storage/mcp_service/src/tool_service.rs
+++ b/rust/cloud-storage/mcp_service/src/tool_service.rs
@@ -148,7 +148,7 @@ where
let user_id = Self::authenticated_user_id(&context.extensions)?;
self.require_paid_subscription(&user_id).await?;
- let request_context = RequestContext { user_id };
+ let request_context = RequestContext::new(user_id);
let arguments = request
.arguments
diff --git a/rust/cloud-storage/prompt/src/connected_toolsets.rs b/rust/cloud-storage/prompt/src/connected_toolsets.rs
new file mode 100644
index 0000000000..da6d915c21
--- /dev/null
+++ b/rust/cloud-storage/prompt/src/connected_toolsets.rs
@@ -0,0 +1,78 @@
+//! Tells the model which connected integrations (MCP toolsets) are available
+//! to discover via tool search.
+//!
+//! Tools from the user's connected MCP servers are NOT advertised on every
+//! request — they are loaded on demand via the `SearchTools` / `LoadTools`
+//! tools (see the tool-search mechanism). The downside is that nothing in the
+//! request tells the model those integrations exist, so it never thinks to
+//! search for them. This section closes that gap by naming the toolsets the
+//! user actually has connected and instructing the model to use tool search to
+//! reach their tools when a task calls for it.
+//!
+//! The set of connected toolsets is per-user and only known at request time, so
+//! this section is rendered by [`render`] rather than declared as a `'static`
+//! prompt.
+
+static TITLE: &str = "Connected Integrations";
+
+/// Renders the connected-integrations section, listing the `names` of the
+/// toolsets (MCP servers) the user currently has connected and instructing the
+/// model to reach their tools via `SearchTools` / `LoadTools`.
+///
+/// Returns `None` when `names` is empty — there is nothing to discover, so the
+/// section is omitted rather than emitting an empty, confusing block. Names are
+/// rendered in the order given (callers should pass them de-duplicated and
+/// sorted for a stable prompt).
+pub fn render(names: &[String]) -> Option<String> {
+ if names.is_empty() {
+ return None;
+ }
+
+ let list = names
+ .iter()
+ .map(|name| format!("- {name}"))
+ .collect::<Vec<_>>()
+ .join("\n");
+
+ Some(format!(
+ "# {TITLE}\n\
+ You have these integrations connected:\n\
+ {list}\n\
+ \n\
+ Their individual tools are NOT all listed upfront. When a task might \
+ need a capability from one of these integrations: (1) call \
+ `SearchTools` with keywords (e.g. \"linear issue\", \"github commits\") \
+ to find matching tools by name and description; (2) call `LoadTools` \
+ with the names you want to make them callable; (3) call the loaded tool \
+ by its name. Searching is cheap — search broadly, then load only what \
+ you need. Think about whether a connected integration is relevant \
+ before answering from what you already have; e.g. a question about \
+ recent work may be answerable from a connected issue tracker or code \
+ host even though those tools aren't visible yet.\n"
+ ))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn empty_names_omit_the_section() {
+ assert!(render(&[]).is_none());
+ }
+
+ #[test]
+ fn lists_each_connected_toolset_name() {
+ let section = render(&["Linear".to_string(), "GitHub".to_string()]).unwrap();
+ assert!(section.contains(&format!("# {TITLE}")));
+ assert!(section.contains("- Linear"));
+ assert!(section.contains("- GitHub"));
+ }
+
+ #[test]
+ fn instructs_the_model_to_use_tool_search() {
+ let section = render(&["Slack".to_string()]).unwrap();
+ assert!(section.contains("SearchTools"));
+ assert!(section.contains("LoadTools"));
+ }
+}
diff --git a/rust/cloud-storage/prompt/src/lib.rs b/rust/cloud-storage/prompt/src/lib.rs
index a241c58b2b..4625de6b59 100644
--- a/rust/cloud-storage/prompt/src/lib.rs
+++ b/rust/cloud-storage/prompt/src/lib.rs
@@ -8,6 +8,7 @@
pub mod about_macro;
pub mod channel_mention;
pub mod citations;
+pub mod connected_toolsets;
pub mod do_not;
pub mod math;
pub mod mcp_item_links;