Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(ai): user tools (#2027)
Eric Hayesf918a137173e
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 125ca03d04..0cb661eeb5 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -2792,6 +2792,7 @@ dependencies = ["ai","ai_format","ai_tools",+ "ai_toolset","anyhow","async-openai","async-stream",diff --git a/rust/cloud-storage/ai_tools/src/prompts/all_tools.md b/rust/cloud-storage/ai_tools/src/prompts/all_tools.mdindex 2221c4a9c6..3776c2e102 100644--- a/rust/cloud-storage/ai_tools/src/prompts/all_tools.md+++ b/rust/cloud-storage/ai_tools/src/prompts/all_tools.md@@ -112,6 +112,10 @@ If no inline or node ids are present:# Tool Use+- User tools are tools that must be executed by a user on the frontend.+ A user tool will return "PendingUserExecution" until a user chooses to+ accept / reject the tool.+- Use tools often and specifically.- Prefer precise filters (domain names, IDs) over generic queries.- Web tool expects natural language queries.diff --git a/rust/cloud-storage/ai_toolset/src/toolset/tool_object/mod.rs b/rust/cloud-storage/ai_toolset/src/toolset/tool_object/mod.rsindex 03ec363b67..c00ecfeb73 100644--- a/rust/cloud-storage/ai_toolset/src/toolset/tool_object/mod.rs+++ b/rust/cloud-storage/ai_toolset/src/toolset/tool_object/mod.rs@@ -9,8 +9,10 @@ mod util;mod json_tool;mod object;mod tool_async;+mod user_tool;pub use json_tool::*;pub use object::*;pub use tool_async::*;+pub use user_tool::*;pub use util::*;diff --git a/rust/cloud-storage/ai_toolset/src/toolset/tool_object/user_tool.rs b/rust/cloud-storage/ai_toolset/src/toolset/tool_object/user_tool.rsnew file mode 100644index 0000000000..3d36a626da--- /dev/null+++ b/rust/cloud-storage/ai_toolset/src/toolset/tool_object/user_tool.rs@@ -0,0 +1,54 @@+//! A user tool is a tool that's executed by a user instead of an agent loop+//! A user tool transforms a `T: AsyncTool<Context>::call(..) -> R` into `T: AsyncTool<Context>::call(..) -> Defer`+//! A user execues a tool T by posting to /tools/call/{:tool_id} with body appliction/json T+//! User tools are _opaque_ to the tool loop. IE it will call the `call` method like it would+//! for any other tool, but the call method won't trigger execution+use crate::{AsyncTool, ToolResult};+use crate::{RequestContext, ServiceContext};+use async_trait::async_trait;+use schemars::JsonSchema;+use serde::{Deserialize, Serialize};++/// User tool wrapper type that implements stubs [`AsyncTool`]+#[derive(Serialize, Deserialize)]+#[serde(transparent)]+pub struct UserTool<T>(pub T);++impl<T: JsonSchema> JsonSchema for UserTool<T> {+ fn schema_name() -> std::borrow::Cow<'static, str> {+ T::schema_name()+ }+ fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {+ T::json_schema(generator)+ }+}++/// User tools are pending until a user executes them+#[derive(Serialize, JsonSchema)]+pub enum UserToolResult<T: Serialize + 'static> {+ /// Tool has not yet been executed+ PendingUserExecution,+ /// Tool is executed and has whatever return type the wrapped tool returns+ Executed(T),+ /// User rejected suggested tool execution+ Rejected,+}++#[async_trait]+impl<T, Context> AsyncTool<Context> for UserTool<T>+where+ T: AsyncTool<Context>,+ T: Send + Sync + 'static + for<'de> Deserialize<'de>,+ Context: Send + Sync + 'static,+{+ type Output = UserToolResult<T::Output>;++ /// Calling a user tool doesn't do anything+ async fn call(+ &self,+ _service_context: ServiceContext<Context>,+ _request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ ToolResult::Ok(UserToolResult::PendingUserExecution)+ }+}diff --git a/rust/cloud-storage/ai_toolset/src/toolset/types.rs b/rust/cloud-storage/ai_toolset/src/toolset/types.rsindex 134df637a7..dc482ecdf3 100644--- a/rust/cloud-storage/ai_toolset/src/toolset/types.rs+++ b/rust/cloud-storage/ai_toolset/src/toolset/types.rs@@ -1,5 +1,5 @@//! types-use super::tool_object::{AsyncToolObject, ValidationError};+use super::tool_object::{AsyncToolObject, UserTool, ValidationError};use crate::RequestContext;use crate::{AsyncTool, ToolResult};use axum::extract::FromRef;@@ -62,7 +62,10 @@ impl ToolSchema {#[derive(Default)]pub struct ToolSet<T> {/// The tools in this toolset, keyed by name.+ /// This includes type-erased user toolspub tools: HashMap<String, T>,+ /// Non type-erased user tools+ pub user_tools: HashMap<String, T>,}impl<T> ToolSet<T> {@@ -70,6 +73,7 @@ impl<T> ToolSet<T> {pub fn new() -> Self {Self {tools: HashMap::new(),+ user_tools: HashMap::new(),}}}@@ -117,6 +121,25 @@ where}}+ /// Adds a user tool to the toolset+ /// A user tool isn't executed automatically by default+ pub fn add_user_tool<T, ToolContext>(mut self) -> Result<Self, ToolSetCreationError>+ where+ ToolContext: Sync + Send + FromRef<ToolSetContext> + 'static,+ T: JsonSchema + AsyncTool<ToolContext> + for<'de> Deserialize<'de> + 'static + Send + Sync,+ T::Output: Serialize + JsonSchema + 'static,+ {+ let tool_object = AsyncToolObject::try_from_tool::<T, ToolContext, T::Output>()+ .map_err(ToolSetCreationError::Validation)?;+ if self.user_tools.contains_key(&tool_object.name) {+ return Err(ToolSetCreationError::NameConflict(tool_object.name.clone()));+ } else {+ self.user_tools+ .insert(tool_object.name.clone(), tool_object);+ }+ self.add_tool::<UserTool<T>, ToolContext>()+ }+/// Attempts to call a tool by name with the given JSON input.////// The tool will automatically extract its specific context from the provided@@ -143,6 +166,26 @@ whereOk(tool.call(context, request_context).await)}+ /// this isn't called in the tool loop it's calle by the user-facing API+ #[tracing::instrument(err, skip(self, context, request_context))]+ pub async fn try_user_tool_call(+ &self,+ context: ToolSetContext,+ request_context: RequestContext,+ tool_name: &str,+ json: &serde_json::Value,+ ) -> Result<ToolResult<serde_json::Value>, ToolSetError> {+ let tool = self+ .user_tools+ .get(tool_name)+ .ok_or_else(|| ToolSetError::NotFound(tool_name.to_owned()))+ .and_then(|tool| {+ tool.try_deserialize(json)+ .map_err(ToolSetError::Deserialization)+ })?;+ Ok(tool.call(context, request_context).await)+ }+/// Merges a subtoolset with a narrower context into this toolset.////// The subtoolset's context type (`SubContext`) must be derivable from thisdiff --git a/rust/cloud-storage/document_cognition_service/.sqlx/query-2be663b7a621a105dd9989f13ede43e03f3c8d625e89eb48ae2b18fdf246eed3.json b/rust/cloud-storage/document_cognition_service/.sqlx/query-2be663b7a621a105dd9989f13ede43e03f3c8d625e89eb48ae2b18fdf246eed3.jsonnew file mode 100644index 0000000000..96670023b9--- /dev/null+++ b/rust/cloud-storage/document_cognition_service/.sqlx/query-2be663b7a621a105dd9989f13ede43e03f3c8d625e89eb48ae2b18fdf246eed3.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id, content\n FROM \"ChatMessage\"\n WHERE \"chatId\" = $1\n ORDER BY \"createdAt\" ASC\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "content",+ "type_info": "Jsonb"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "2be663b7a621a105dd9989f13ede43e03f3c8d625e89eb48ae2b18fdf246eed3"+}diff --git a/rust/cloud-storage/document_cognition_service/.sqlx/query-8998b4b11957d70a3c2dbd6497037e1e761aa30599390e4902eccb12a7867834.json b/rust/cloud-storage/document_cognition_service/.sqlx/query-8998b4b11957d70a3c2dbd6497037e1e761aa30599390e4902eccb12a7867834.jsonnew file mode 100644index 0000000000..daea510aab--- /dev/null+++ b/rust/cloud-storage/document_cognition_service/.sqlx/query-8998b4b11957d70a3c2dbd6497037e1e761aa30599390e4902eccb12a7867834.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE \"ChatMessage\"\n SET \"content\" = $1, \"updatedAt\" = NOW()\n WHERE \"id\" = $2\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Jsonb",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "8998b4b11957d70a3c2dbd6497037e1e761aa30599390e4902eccb12a7867834"+}diff --git a/rust/cloud-storage/document_cognition_service/Cargo.toml b/rust/cloud-storage/document_cognition_service/Cargo.tomlindex 011bb4c44a..c65dc43a4d 100644--- a/rust/cloud-storage/document_cognition_service/Cargo.toml+++ b/rust/cloud-storage/document_cognition_service/Cargo.toml@@ -34,6 +34,7 @@ async-trait = { workspace = true }ai = { path = "../ai" }ai_format = { path = "../ai_format" }ai_tools = { path = "../ai_tools" }+ai_toolset = { path = "../ai_toolset" }anyhow = { workspace = true }async-openai = { workspace = true }aws-sdk-secretsmanager = { workspace = true }diff --git a/rust/cloud-storage/document_cognition_service/src/api/chats/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/chats/mod.rsindex 9ce1c194d2..3e176ea885 100644--- a/rust/cloud-storage/document_cognition_service/src/api/chats/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/chats/mod.rs@@ -7,6 +7,7 @@ pub mod get_chat;pub mod get_chat_permissions;pub mod patch_chat;pub mod revert_delete_chat;+pub mod tool;use super::context::ApiContext;use axum::{@@ -105,6 +106,16 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {.layer(ensure_chat_exists.clone()),),)+ .nest(+ "/{chat_id}/tool",+ tool::router().layer(+ ServiceBuilder::new()+ .layer(axum::middleware::from_fn(+ macro_middleware::auth::ensure_user_exists::handler,+ ))+ .layer(ensure_chat_exists.clone()),+ ),+ ).route("/history/{chat_id}",get(chat_history::get_chat_history_handler).layer(diff --git a/rust/cloud-storage/document_cognition_service/src/api/chats/tool/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/chats/tool/mod.rsnew file mode 100644index 0000000000..6a4a4f3982--- /dev/null+++ b/rust/cloud-storage/document_cognition_service/src/api/chats/tool/mod.rs@@ -0,0 +1,8 @@+mod post;++use crate::api::context::ApiContext;+use axum::{Router, routing::post};++pub fn router() -> Router<ApiContext> {+ Router::new().route("/", post(post::handler))+}diff --git a/rust/cloud-storage/document_cognition_service/src/api/chats/tool/post.rs b/rust/cloud-storage/document_cognition_service/src/api/chats/tool/post.rsnew file mode 100644index 0000000000..ea75f973cd--- /dev/null+++ b/rust/cloud-storage/document_cognition_service/src/api/chats/tool/post.rs@@ -0,0 +1,280 @@+// This API is designed to suppot "user tools". These are tools that give the user+// the choice to accept/reject as well as the option to edit a tool before it's executed.+//+// The AI will generate a tool call and stub it's response with "pending" then continue+// executing.+//+// If a user likes the tool result and wants to execute the tool they'll hit this API.+// This API will execute the tool. It will use the message chain as the source of truth / storage+// which will be a bit of an ugly implementation. This means that if the user chooses to reject+// the response should be update fromp pending -> rejected. If the user chooses to execute the tool+// the response should be appropriately updated to reflect the result.+//+// The API supports edits by taking an optional "args" field that must match the shape of the named tool.+// The toolset will validate this shape for you. In the case that args are provided _both_ the response+// and call need to be updated+//+// You'll need to write some SQLX queries to do all of this. Put each query in it's own function. Put queries+// in the service module of this crate.+//+use crate::api::context::ApiContext;+use crate::service::tool::{get_chat_messages, update_message_content};+use ai::types::{AssistantMessagePart, ChatMessageContent};+use ai_tools::{RequestContext, ToolServiceContext, all_tools};+use ai_toolset::tool_object::UserToolResult;+use axum::extract::{Json, Path, State};+use axum::http::StatusCode;+use axum::response::{IntoResponse, Response};+use entity_access::domain::models::OwnerAccessLevel;+use macro_middleware::cloud_storage::ensure_access::chat::ChatAccessLevelExtractor;+use model::user::axum_extractor::MacroUserExtractor;+use serde::{Deserialize, Serialize};+use serde_json::Value;+use std::sync::Arc;++#[derive(Debug, Serialize, Deserialize)]+#[serde(tag = "action", rename_all = "lowercase")]+pub enum ToolPostRequest {+ Reject {+ tool_id: String,+ },+ Accept {+ tool_id: String,+ args: Option<Value>,+ },+}++impl ToolPostRequest {+ pub fn tool_id(&self) -> &str {+ match self {+ Self::Accept { tool_id, .. } | Self::Reject { tool_id, .. } => tool_id,+ }+ }+}++#[derive(Serialize)]+struct ToolPostResponse {+ result: Value,+}++/// execute a saved tool+#[utoipa::path(+ post,+ path = "/chats/{chat_id}/tool",+ request_body = Value,+ responses(+ (status = 200, body = Value),+ (status = 404, body = String),+ (status = 500, body = String),+ ),+ params(+ ("chat_id" = String, Path, description = "Chat id")+ )+)]+#[tracing::instrument(skip(state, user, _access), fields(user_id=?user.macro_user_id))]+pub async fn handler(+ _access: ChatAccessLevelExtractor<OwnerAccessLevel>,+ State(state): State<ApiContext>,+ user: MacroUserExtractor,+ Path(chat_id): Path<String>,+ Json(request): Json<ToolPostRequest>,+) -> Result<Response, Response> {+ let messages = get_chat_messages(&state.db, &chat_id)+ .await+ .inspect_err(|e| tracing::error!(error=?e, "failed to fetch chat messages"))+ .map_err(|_| {+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ "failed to fetch chat messages",+ )+ .into_response()+ })?;++ let tool_id = request.tool_id().to_owned();++ // Find the message containing the tool call with this ID+ let (message_id, mut parts) = messages+ .into_iter()+ .find_map(|msg| match msg.content {+ ChatMessageContent::AssistantMessageParts(parts) => {+ let has_tool = parts.iter().any(|part| {+ matches!(+ part,+ AssistantMessagePart::ToolCall { id, .. } if *id == tool_id+ )+ });+ if has_tool {+ Some((msg.id, parts))+ } else {+ None+ }+ }+ _ => None,+ })+ .ok_or_else(|| (StatusCode::NOT_FOUND, "tool call not found").into_response())?;++ // Extract tool name and original args from the tool call+ let (tool_name, original_args) = parts+ .iter()+ .find_map(|part| match part {+ AssistantMessagePart::ToolCall { name, json, id } if *id == tool_id => {+ Some((name.clone(), json.clone()))+ }+ _ => None,+ })+ .expect("tool call must exist since we found the message above");++ match request {+ ToolPostRequest::Reject { .. } => {+ // Update the tool response from Pending -> Rejected+ let rejected = serde_json::to_value(UserToolResult::<Value>::Rejected)+ .expect("UserToolResult serialization cannot fail");+ update_tool_response(&mut parts, &tool_id, rejected);++ let content = ChatMessageContent::AssistantMessageParts(parts);+ update_message_content(&state.db, &message_id, &content)+ .await+ .inspect_err(|e| tracing::error!(error=?e, "failed to update message content"))+ .map_err(|_| {+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ "failed to update message",+ )+ .into_response()+ })?;++ Ok(StatusCode::OK.into_response())+ }+ ToolPostRequest::Accept { args, .. } => {+ let exec_args = args.as_ref().unwrap_or(&original_args);++ // If user provided custom args, update the tool call args+ if let Some(ref custom_args) = args {+ update_tool_call_args(&mut parts, &tool_id, custom_args.clone());+ }++ // Construct toolset and execute+ let toolset = all_tools().toolset;++ let tool_context = ToolServiceContext {+ email_service_client: state.email_service_client_external.clone(),+ search_service_client: state.search_service_client.clone(),+ scribe: state.scribe.clone(),+ soup_service: state.soup_service.clone(),+ document_tool_context: state.document_tool_context.clone(),+ };++ #[expect(deprecated)]+ let request_context = RequestContext {+ user_id: Arc::new(user.macro_user_id),+ jwt: Arc::new(String::new()),+ };++ let tool_result = toolset+ .try_user_tool_call(tool_context, request_context, &tool_name, exec_args)+ .await+ .map_err(|e| {+ tracing::error!(error=?e, "toolset error");+ (StatusCode::BAD_REQUEST, e.to_string()).into_response()+ })?;++ let response_json = match tool_result {+ Ok(result) => serde_json::to_value(UserToolResult::Executed(result))+ .expect("UserToolResult serialization cannot fail"),+ Err(tool_err) => {+ tracing::error!(error=?tool_err.internal_error, "tool execution failed");++ // Replace the response with a ToolCallErr+ replace_tool_response_with_err(+ &mut parts,+ &tool_id,+ &tool_name,+ &tool_err.description,+ );++ let content = ChatMessageContent::AssistantMessageParts(parts);+ update_message_content(&state.db, &message_id, &content)+ .await+ .inspect_err(+ |e| tracing::error!(error=?e, "failed to update message after tool error"),+ )+ .map_err(|_| {+ (StatusCode::INTERNAL_SERVER_ERROR, "failed to update message")+ .into_response()+ })?;++ return Err(+ (StatusCode::UNPROCESSABLE_ENTITY, tool_err.description).into_response()+ );+ }+ };++ update_tool_response(&mut parts, &tool_id, response_json.clone());++ let content = ChatMessageContent::AssistantMessageParts(parts);+ update_message_content(&state.db, &message_id, &content)+ .await+ .inspect_err(|e| tracing::error!(error=?e, "failed to update message content"))+ .map_err(|_| {+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ "failed to update message",+ )+ .into_response()+ })?;++ Ok((+ StatusCode::OK,+ Json(ToolPostResponse {+ result: response_json,+ }),+ )+ .into_response())+ }+ }+}++/// Updates the json field of the ToolCallResponseJson part matching the given tool_id.+fn update_tool_response(parts: &mut [AssistantMessagePart], tool_id: &str, new_json: Value) {+ for part in parts.iter_mut() {+ if let AssistantMessagePart::ToolCallResponseJson { id, json, .. } = part+ && id == tool_id+ {+ *json = new_json;+ return;+ }+ }+}++/// Updates the json (args) field of the ToolCall part matching the given tool_id.+fn update_tool_call_args(parts: &mut [AssistantMessagePart], tool_id: &str, new_args: Value) {+ for part in parts.iter_mut() {+ if let AssistantMessagePart::ToolCall { id, json, .. } = part+ && id == tool_id+ {+ *json = new_args;+ return;+ }+ }+}++/// Replaces a ToolCallResponseJson with a ToolCallErr for the given tool_id.+fn replace_tool_response_with_err(+ parts: &mut [AssistantMessagePart],+ tool_id: &str,+ tool_name: &str,+ description: &str,+) {+ for part in parts.iter_mut() {+ if let AssistantMessagePart::ToolCallResponseJson { id, .. } = part+ && id == tool_id+ {+ *part = AssistantMessagePart::ToolCallErr {+ name: tool_name.to_string(),+ description: description.to_string(),+ id: tool_id.to_string(),+ };+ return;+ }+ }+}diff --git a/rust/cloud-storage/document_cognition_service/src/service/mod.rs b/rust/cloud-storage/document_cognition_service/src/service/mod.rsindex a1b0d77854..c85dfe6ec2 100644--- a/rust/cloud-storage/document_cognition_service/src/service/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/service/mod.rs@@ -2,3 +2,4 @@ pub mod attachment;pub mod get_chat;pub mod id_mapping;pub mod notification;+pub mod tool;diff --git a/rust/cloud-storage/document_cognition_service/src/service/tool.rs b/rust/cloud-storage/document_cognition_service/src/service/tool.rsnew file mode 100644index 0000000000..1e4e6acef9--- /dev/null+++ b/rust/cloud-storage/document_cognition_service/src/service/tool.rs@@ -0,0 +1,65 @@+use ai::types::ChatMessageContent;+use anyhow::Result;+use sqlx::{Executor, Postgres};++/// A chat message with only the fields needed for tool operations.+pub struct ToolMessage {+ pub id: String,+ pub content: ChatMessageContent,+}++/// Fetches all messages for a chat, returning only id and content.+#[tracing::instrument(err, skip(db))]+pub async fn get_chat_messages<'e, T>(db: T, chat_id: &str) -> Result<Vec<ToolMessage>>+where+ T: Executor<'e, Database = Postgres>,+{+ let rows = sqlx::query!(+ r#"+ SELECT id, content+ FROM "ChatMessage"+ WHERE "chatId" = $1+ ORDER BY "createdAt" ASC+ "#,+ chat_id+ )+ .fetch_all(db)+ .await?;++ rows.into_iter()+ .map(|row| {+ let content = serde_json::from_value::<ChatMessageContent>(row.content)?;+ Ok(ToolMessage {+ id: row.id,+ content,+ })+ })+ .collect()+}++/// Updates the content of a specific chat message.+#[tracing::instrument(err, skip(db, content))]+pub async fn update_message_content<'e, T>(+ db: T,+ message_id: &str,+ content: &ChatMessageContent,+) -> Result<()>+where+ T: Executor<'e, Database = Postgres>,+{+ let content_json = serde_json::to_value(content)?;++ sqlx::query!(+ r#"+ UPDATE "ChatMessage"+ SET "content" = $1, "updatedAt" = NOW()+ WHERE "id" = $2+ "#,+ content_json,+ message_id+ )+ .execute(db)+ .await?;++ Ok(())+}