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(ai): document ai tool (#1527)

Will Hutchinson9d9a5b139740
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 25f497cedf..64550d72c4 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -2895,23 +2895,30 @@ dependencies = [
name = "documents"
version = "0.1.0"
dependencies = [
+ "ai",
"anyhow",
+ "async-trait",
"axum",
"axum-extra",
"chrono",
"cloudfront_sign",
"document_sub_type",
+ "dotenvy",
"entity_access",
"futures",
"http-body-util",
+ "lexical_client",
"macro_db_migrator",
"macro_project_utils",
"macro_user_id",
"mockall",
"model",
"model-error-response",
+ "model_file_type",
"model_user",
"models_permissions",
+ "reqwest",
+ "schemars",
"serde",
"serde_json",
"sqlx",
diff --git a/rust/cloud-storage/documents/.sqlx/query-28c518d844cd4d843c097af1551f6f384a4763514d278b5444341390f58a8281.json b/rust/cloud-storage/documents/.sqlx/query-28c518d844cd4d843c097af1551f6f384a4763514d278b5444341390f58a8281.json
deleted file mode 100644
index 98ceb2aeec..0000000000
--- a/rust/cloud-storage/documents/.sqlx/query-28c518d844cd4d843c097af1551f6f384a4763514d278b5444341390f58a8281.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "UPDATE \"Project\" SET \"updatedAt\" = NOW() WHERE id = $1",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "28c518d844cd4d843c097af1551f6f384a4763514d278b5444341390f58a8281"
-}
diff --git a/rust/cloud-storage/documents/.sqlx/query-5f9f23e45c696db3baa3b172efb66ba931aeb9036344782bd4a5e277df2c7ce2.json b/rust/cloud-storage/documents/.sqlx/query-5f9f23e45c696db3baa3b172efb66ba931aeb9036344782bd4a5e277df2c7ce2.json
new file mode 100644
index 0000000000..026cb1931b
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-5f9f23e45c696db3baa3b172efb66ba931aeb9036344782bd4a5e277df2c7ce2.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n d.content\n FROM\n \"DocumentText\" d\n WHERE\n d.\"documentId\" = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "content",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "5f9f23e45c696db3baa3b172efb66ba931aeb9036344782bd4a5e277df2c7ce2"
+}
diff --git a/rust/cloud-storage/documents/Cargo.toml b/rust/cloud-storage/documents/Cargo.toml
index cff8ee17b4..5948d35606 100644
--- a/rust/cloud-storage/documents/Cargo.toml
+++ b/rust/cloud-storage/documents/Cargo.toml
@@ -5,10 +5,20 @@ publish = false
version = "0.1.0"
[features]
-default = ["ports", "inbound", "outbound", "axum"]
+default = ["ports", "inbound", "outbound", "axum", "ai_tools"]
ports = ["dep:tokio"]
inbound = ["axum", "ports"]
outbound = ["ports"]
+ai_tools = [
+ "dep:ai",
+ "dep:async-trait",
+ "dep:schemars",
+ "dep:lexical_client",
+ "dep:model_file_type",
+ "dep:reqwest",
+ "ports",
+ "outbound"
+]
axum = [
"dep:axum",
"dep:axum-extra",
@@ -53,6 +63,14 @@ sqlx = { workspace = true }
sync_service_client = { path = "../sync_service_client" }
urlencoding = { workspace = true }
+# AI Tool dependencies
+ai = { path = "../ai", optional = true }
+async-trait = { workspace = true, optional = true }
+schemars = { workspace = true, optional = true }
+lexical_client = { path = "../lexical_client", optional = true }
+model_file_type = { path = "../model_file_type", optional = true }
+reqwest = { workspace = true, optional = true }
+
[dev-dependencies]
http-body-util = { workspace = true }
macro_db_migrator = { path = "../macro_db_migrator" }
@@ -60,3 +78,4 @@ mockall = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
tower = { workspace = true }
+dotenvy = { workspace = true }
diff --git a/rust/cloud-storage/documents/examples/documents_toolset.rs b/rust/cloud-storage/documents/examples/documents_toolset.rs
new file mode 100644
index 0000000000..09a994ed0f
--- /dev/null
+++ b/rust/cloud-storage/documents/examples/documents_toolset.rs
@@ -0,0 +1,112 @@
+//! CLI example for testing documents AI tools interactively.
+//!
+//! This example creates a CLI interface to test the documents toolset with real database connections.
+//!
+//! # Usage
+//!
+//! ```bash
+//! DATABASE_URL=postgres://...
+//! ANTHROPIC_API_KEY=sk_abcdefl...
+//! LOCAL_USER_ID=macro|<email>
+//! SYNC_SERVICE_URL=...
+//! SYNC_SERVICE_AUTH_KEY=...
+//! DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_DISTRIBUTION_URL=...
+//! DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME=THE PRIVATE KEY
+//! DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PUBLIC_KEY_ID=...
+//! cargo run --example documents_toolset
+//! ```
+
+use ai::tool::tool_loop::cli::Cli;
+use ai::tool::types::RequestContext;
+use ai::types::Model;
+use documents::domain::models::CloudFrontConfig;
+use documents::domain::service::DocumentServiceImpl;
+use documents::inbound::toolset::{DocumentToolContext, document_toolset};
+use documents::outbound::pg_document_repo::PgDocumentRepo;
+use entity_access::domain::service::EntityAccessServiceImpl;
+use entity_access::outbound::PgAccessRepository;
+use lexical_client::LexicalClient;
+use macro_user_id::user_id::MacroUserIdStr;
+use sqlx::PgPool;
+use std::sync::Arc;
+use sync_service_client::SyncServiceClient;
+
+/// The prompt to use in the example.
+const PROMPT: &str = "You are an assistant that helps users explore and manage their documents. Use the available tools to read document metadata.";
+
+#[tokio::main]
+async fn main() {
+ dotenvy::dotenv().ok();
+ // Get database URL from environment
+ let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
+ let usr = std::env::var("LOCAL_USER_ID").expect("LOCAL_USER_ID must bes set");
+ let user_id: MacroUserIdStr<'static> = usr.try_into().expect("valid user id macro|<email>");
+
+ let sync_service_url = std::env::var("SYNC_SERVICE_URL").expect("SYNC_SERVICE_URL must be set");
+ let lexical_service_url =
+ std::env::var("LEXICAL_SERVICE_URL").expect("LEXICAL_SERVICE_URL must be set");
+ let sync_service_auth_key =
+ std::env::var("SYNC_SERVICE_AUTH_KEY").expect("SYNC_SERVICE_AUTH_KEY must be set");
+
+ println!(
+ "Running with\nuser [{}]\ndatabase [{}]",
+ user_id, database_url
+ );
+
+ // Connect to the database
+ let pool = PgPool::connect(&database_url)
+ .await
+ .expect("Failed to connect to database");
+
+ let entity_access_repo = PgAccessRepository::new(pool.clone());
+ let entity_access_service = EntityAccessServiceImpl::new(entity_access_repo);
+
+ let documents_repo = PgDocumentRepo::new(pool.clone());
+ let documents_service = DocumentServiceImpl::new(
+ documents_repo,
+ CloudFrontConfig {
+ distribution_url: std::env::var("DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_DISTRIBUTION_URL")
+ .expect("DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_DISTRIBUTION_URL must be set"),
+ signer_public_key_id: std::env::var(
+ "DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PUBLIC_KEY_ID",
+ )
+ .expect("DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PUBLIC_KEY_ID must be set"),
+ signer_private_key: std::env::var(
+ "DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME",
+ )
+ .expect(
+ "DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME must be set",
+ ),
+ presigned_url_expiry_seconds: 840,
+ browser_cache_expiry_seconds: 900,
+ },
+ SyncServiceClient::new(sync_service_auth_key.clone(), sync_service_url),
+ pool,
+ );
+
+ let lexical_client = LexicalClient::new(sync_service_auth_key, lexical_service_url);
+
+ let document_tool_context =
+ DocumentToolContext::new(documents_service, entity_access_service, lexical_client);
+
+ let toolset = document_toolset();
+
+ let context = RequestContext {
+ user_id: Arc::new(user_id),
+ // Remove this later
+ #[allow(deprecated)]
+ jwt: Arc::new(String::new()),
+ };
+
+ // Create the CLI
+ let cli = Cli::new(
+ toolset,
+ document_tool_context,
+ PROMPT,
+ Model::Claude45Haiku,
+ move || context.clone(),
+ );
+
+ // Run the CLI
+ cli.run().await;
+}
diff --git a/rust/cloud-storage/documents/justfile b/rust/cloud-storage/documents/justfile
index d5a52bc432..d7f13030d3 100644
--- a/rust/cloud-storage/documents/justfile
+++ b/rust/cloud-storage/documents/justfile
@@ -4,3 +4,6 @@ mod sqlx '../sqlx.just'
prepare_db:
just sqlx::prepare_db {{ DATABASE_URL }}
+
+check:
+ cargo check --all-features
diff --git a/rust/cloud-storage/documents/src/domain/ports.rs b/rust/cloud-storage/documents/src/domain/ports.rs
index a6c83be438..3876ac29b1 100644
--- a/rust/cloud-storage/documents/src/domain/ports.rs
+++ b/rust/cloud-storage/documents/src/domain/ports.rs
@@ -69,6 +69,12 @@ pub trait DocumentRepo: Send + Sync + 'static {
&self,
document_id: &str,
) -> impl Future<Output = Result<Vec<String>, Self::Err>> + Send;
+
+ /// Get document text by document ID
+ fn get_document_text(
+ &self,
+ document_id: &str,
+ ) -> impl Future<Output = Result<String, Self::Err>> + Send;
}
/// Service interface for document operations.
@@ -101,4 +107,10 @@ pub trait DocumentService: Send + Sync + 'static {
entity_access_receipt: EntityAccessReceipt,
project_id: Option<String>,
) -> impl Future<Output = Result<(), DocumentError>> + Send;
+
+ /// Get the document text for a given document
+ fn get_document_text(
+ &self,
+ entity_access_receipt: EntityAccessReceipt,
+ ) -> impl Future<Output = Result<String, DocumentError>> + Send;
}
diff --git a/rust/cloud-storage/documents/src/domain/service.rs b/rust/cloud-storage/documents/src/domain/service.rs
index dfab316b99..f8ea2bd3eb 100644
--- a/rust/cloud-storage/documents/src/domain/service.rs
+++ b/rust/cloud-storage/documents/src/domain/service.rs
@@ -362,7 +362,7 @@ impl<R: DocumentRepo> DocumentService for DocumentServiceImpl<R> {
project_id: Option<String>,
) -> Result<(), DocumentError> {
self.repo
- .soft_delete_document(&entity_access_receipt.entity().entity_id)
+ .soft_delete_document(&entity_access_receipt.entity().entity_id.clone())
.await
.map_err(|e| DocumentError::Internal(e.into()))?;
@@ -402,4 +402,14 @@ impl<R: DocumentRepo> DocumentService for DocumentServiceImpl<R> {
}
})
}
+
+ async fn get_document_text(
+ &self,
+ entity_access_receipt: EntityAccessReceipt,
+ ) -> Result<String, DocumentError> {
+ self.repo
+ .get_document_text(&entity_access_receipt.entity().entity_id)
+ .await
+ .map_err(|e| DocumentError::Internal(e.into()))
+ }
}
diff --git a/rust/cloud-storage/documents/src/inbound.rs b/rust/cloud-storage/documents/src/inbound.rs
index 45c679928b..97b86a8e0b 100644
--- a/rust/cloud-storage/documents/src/inbound.rs
+++ b/rust/cloud-storage/documents/src/inbound.rs
@@ -2,3 +2,6 @@
#[cfg(feature = "axum")]
pub mod axum_router;
+
+#[cfg(feature = "ai_tools")]
+pub mod toolset;
diff --git a/rust/cloud-storage/documents/src/inbound/toolset/mod.rs b/rust/cloud-storage/documents/src/inbound/toolset/mod.rs
new file mode 100644
index 0000000000..f72aa70274
--- /dev/null
+++ b/rust/cloud-storage/documents/src/inbound/toolset/mod.rs
@@ -0,0 +1,61 @@
+//! Toolset inbound adapter for Documents.
+
+mod read_content;
+mod read_metadata;
+
+#[cfg(test)]
+mod test;
+
+use crate::{
+ domain::ports::DocumentService,
+ inbound::toolset::{read_content::ReadContent, read_metadata::ReadMetadata},
+};
+use ai::tool::AsyncToolSet;
+use entity_access::domain::ports::EntityAccessService;
+use lexical_client::LexicalClient;
+use std::sync::Arc;
+
+/// Service context for document AI tools
+pub struct DocumentToolContext<DSvc: DocumentService, ESvc: EntityAccessService> {
+ /// The document service instance
+ pub service: Arc<DSvc>,
+ /// The entity access service instance
+ pub entity_access_service: Arc<ESvc>,
+
+ /// The lexical client
+ pub lexical_client: Arc<LexicalClient>,
+}
+
+impl<DSvc: DocumentService, ESvc: EntityAccessService> Clone for DocumentToolContext<DSvc, ESvc> {
+ fn clone(&self) -> Self {
+ Self {
+ service: self.service.clone(),
+ entity_access_service: self.entity_access_service.clone(),
+ lexical_client: self.lexical_client.clone(),
+ }
+ }
+}
+
+impl<DSvc: DocumentService, ESvc: EntityAccessService> DocumentToolContext<DSvc, ESvc> {
+ /// Create a new document tool context
+ pub fn new(service: DSvc, entity_access_service: ESvc, lexical_client: LexicalClient) -> Self {
+ Self {
+ service: Arc::new(service),
+ entity_access_service: Arc::new(entity_access_service),
+ lexical_client: Arc::new(lexical_client),
+ }
+ }
+}
+
+/// Create a document toolset
+pub fn document_toolset<DSvc, ESvc>() -> AsyncToolSet<DocumentToolContext<DSvc, ESvc>>
+where
+ DSvc: DocumentService,
+ ESvc: EntityAccessService,
+{
+ AsyncToolSet::new()
+ .add_tool::<ReadMetadata, DocumentToolContext<DSvc, ESvc>>()
+ .expect("failed to add ReadMetadata tool")
+ .add_tool::<ReadContent, DocumentToolContext<DSvc, ESvc>>()
+ .expect("failed to add ReadContent tool")
+}
diff --git a/rust/cloud-storage/documents/src/inbound/toolset/read_content.rs b/rust/cloud-storage/documents/src/inbound/toolset/read_content.rs
new file mode 100644
index 0000000000..78dc601ed4
--- /dev/null
+++ b/rust/cloud-storage/documents/src/inbound/toolset/read_content.rs
@@ -0,0 +1,207 @@
+//! ReadContent tool for reading document content.
+
+use std::str::FromStr;
+
+use crate::domain::{models::LocationQueryParams, ports::DocumentService};
+use ai::tool::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
+use async_trait::async_trait;
+use entity_access::domain::{
+ models::{EntityAccessReceipt, EntityType},
+ ports::EntityAccessService,
+};
+use model::document::DocumentBasic;
+use model_file_type::{FileAssociation, FileType};
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+use super::DocumentToolContext;
+
+/// Markdown node
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct MarkdownNode {
+ /// The node id
+ pub node_id: String,
+ /// Human readable content
+ pub content: String,
+ /// Json respresentation
+ pub raw_content: String,
+ /// The style on the node, H1, em, code, etc.
+ pub r#type: String,
+}
+
+impl From<lexical_client::types::MarkdownNode> for MarkdownNode {
+ fn from(value: lexical_client::types::MarkdownNode) -> Self {
+ Self {
+ node_id: value.node_id,
+ content: value.content,
+ raw_content: value.raw_content,
+ r#type: value.r#type,
+ }
+ }
+}
+
+/// The read content response
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub enum ReadContentResponse {
+ /// Simple text content
+ Text(String),
+ /// All nodes of the markdown file
+ Markdown(Vec<MarkdownNode>),
+}
+
+#[derive(Debug, Deserialize, JsonSchema, Clone, Default)]
+#[serde(rename_all = "camelCase")]
+#[schemars(title = "ReadContent", description = "Retrieve a documents content")]
+pub struct ReadContent {
+ #[schemars(description = "The id of the document you want to retrieve content for.")]
+ pub document_id: Uuid,
+}
+
+#[async_trait]
+impl<DSvc, ESvc> AsyncTool<DocumentToolContext<DSvc, ESvc>> for ReadContent
+where
+ DSvc: DocumentService,
+ ESvc: EntityAccessService,
+{
+ type Output = ReadContentResponse;
+
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<DocumentToolContext<DSvc, ESvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ tracing::info!(params=?self, "Read metadata");
+
+ // Get EntityAccessReceipt
+ let entity_access_receipt = service_context
+ .entity_access_service
+ .generate_entity_access_receipt(
+ request_context.user_id.as_ref(),
+ None,
+ &self.document_id.to_string(),
+ EntityType::Document,
+ )
+ .await
+ .map_err(|e| ToolCallError {
+ description: "unable to get the entity access receipt".to_string(),
+ internal_error: e.into(),
+ })?;
+
+ // SAFETY: This is allowed because we have the entity_access_receipt call right above to
+ // ensure the user has access.
+ let document_context = service_context
+ .service
+ .internal_get_basic_document(&self.document_id.to_string())
+ .await
+ .map_err(|e| ToolCallError {
+ description: "unable to get the document context".to_string(),
+ internal_error: e.into(),
+ })?;
+
+ // Based on the file type we need to handle how we get the document differently
+ let file_type: FileType = if let Some(file_type) = document_context.file_type.as_ref() {
+ FileType::from_str(file_type).map_err(|e| ToolCallError {
+ description: format!("unsupported file type {file_type}"),
+ internal_error: e.into(),
+ })?
+ } else {
+ return Err(ToolCallError {
+ description: "cannot get read content for unknown file type".to_string(),
+ internal_error: anyhow::anyhow!("cannot get read content for unknown file type"),
+ });
+ };
+
+ let response: ReadContentResponse = match file_type.macro_app_path() {
+ FileAssociation::Pdf(_) | FileAssociation::Write(_) => ReadContentResponse::Text(
+ service_context
+ .service
+ .get_document_text(entity_access_receipt)
+ .await
+ .map_err(|e| ToolCallError {
+ description: "unable to get document text".to_string(),
+ internal_error: e.into(),
+ })?,
+ ),
+ FileAssociation::Md(_) => ReadContentResponse::Markdown(
+ service_context
+ .lexical_client
+ .parse_markdown_for_ai(&self.document_id.to_string())
+ .await
+ .map_err(|e| ToolCallError {
+ description: "unable to parse markdown".to_string(),
+ internal_error: e,
+ })?
+ .data
+ .into_iter()
+ .map(|i| i.into())
+ .collect(),
+ ),
+ FileAssociation::Code(_) | FileAssociation::Document(_) => ReadContentResponse::Text(
+ get_document_content_from_location(
+ service_context.clone(),
+ &document_context,
+ entity_access_receipt,
+ )
+ .await
+ .map_err(|e| ToolCallError {
+ description: "unable to get document content using location".to_string(),
+ internal_error: e,
+ })?,
+ ),
+ _ => {
+ return Err(ToolCallError {
+ description: format!("unsupported file type {file_type}"),
+ internal_error: anyhow::anyhow!("unsupported file type"),
+ });
+ }
+ };
+
+ Ok(response)
+ }
+}
+
+/// Gets the document content from location
+#[tracing::instrument(skip(service_context), err)]
+async fn get_document_content_from_location<DSvc: DocumentService, ESvc: EntityAccessService>(
+ service_context: ServiceContext<DocumentToolContext<DSvc, ESvc>>,
+ document_context: &DocumentBasic,
+ entity_access_receipt: EntityAccessReceipt,
+) -> anyhow::Result<String> {
+ let location = service_context
+ .service
+ .get_document_location(
+ document_context,
+ entity_access_receipt,
+ LocationQueryParams {
+ get_converted_docx_url: Some(true),
+ document_version_id: None,
+ },
+ )
+ .await?;
+
+ let presigned_url = match location {
+ model::document::response::LocationResponseV3::PresignedUrl {
+ presigned_url,
+ metadata: _metadata,
+ } => presigned_url,
+ // This should only be called with text documents which result in 1 presigned url
+ _ => unreachable!(),
+ };
+
+ // Download the file and convert to UTF8
+ let response = reqwest::get(&presigned_url).await?;
+
+ if !response.status().is_success() {
+ anyhow::bail!("Failed to download document: HTTP {}", response.status());
+ }
+
+ let bytes = response.bytes().await?;
+ let content = String::from_utf8(bytes.to_vec())
+ .map_err(|e| anyhow::anyhow!("Document content is not valid UTF-8: {e}"))?;
+
+ Ok(content)
+}
diff --git a/rust/cloud-storage/documents/src/inbound/toolset/read_metadata.rs b/rust/cloud-storage/documents/src/inbound/toolset/read_metadata.rs
new file mode 100644
index 0000000000..d1b379ff55
--- /dev/null
+++ b/rust/cloud-storage/documents/src/inbound/toolset/read_metadata.rs
@@ -0,0 +1,79 @@
+//! ReadMetadata tool for reading document metadata.
+
+use crate::domain::ports::DocumentService;
+use ai::tool::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
+use async_trait::async_trait;
+use entity_access::domain::{
+ models::{AccessLevel, EntityType},
+ ports::EntityAccessService,
+};
+use model::document::DocumentMetadata;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+use super::DocumentToolContext;
+
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ReadMetadataResponse {
+ /// The metadata of the document
+ pub document_metadata: DocumentMetadata,
+ /// The users level of access to the document
+ pub user_access_level: AccessLevel,
+}
+
+#[derive(Debug, Deserialize, JsonSchema, Clone, Default)]
+#[serde(rename_all = "camelCase")]
+#[schemars(title = "ReadMetadata", description = "Retrieve a documents metadata")]
+pub struct ReadMetadata {
+ #[schemars(description = "The id of the document you want to retrieve metadata for.")]
+ pub document_id: Uuid,
+}
+
+#[async_trait]
+impl<DSvc, ESvc> AsyncTool<DocumentToolContext<DSvc, ESvc>> for ReadMetadata
+where
+ DSvc: DocumentService,
+ ESvc: EntityAccessService,
+{
+ type Output = ReadMetadataResponse;
+
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<DocumentToolContext<DSvc, ESvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ tracing::info!(params=?self, "Read metadata");
+
+ // Get EntityAccessReceipt
+ let entity_access_receipt = service_context
+ .entity_access_service
+ .generate_entity_access_receipt(
+ request_context.user_id.as_ref(),
+ None,
+ &self.document_id.to_string(),
+ EntityType::Document,
+ )
+ .await
+ .map_err(|e| ToolCallError {
+ description: "unable to get the entity access receipt".to_string(),
+ internal_error: e.into(),
+ })?;
+
+ let result = service_context
+ .service
+ .get_document(entity_access_receipt)
+ .await
+ .map_err(|e| ToolCallError {
+ description: "unable to get the document metadata".to_string(),
+ internal_error: e.into(),
+ })?;
+
+ Ok(ReadMetadataResponse {
+ document_metadata: result.document_metadata,
+ user_access_level: result.user_access_level,
+ })
+ }
+}
diff --git a/rust/cloud-storage/documents/src/inbound/toolset/test.rs b/rust/cloud-storage/documents/src/inbound/toolset/test.rs
new file mode 100644
index 0000000000..7c69d5eee8
--- /dev/null
+++ b/rust/cloud-storage/documents/src/inbound/toolset/test.rs
@@ -0,0 +1,39 @@
+use super::*;
+use ai::generate_tool_input_schema;
+use ai::tool::types::tool_object::validate_tool_schema;
+
+#[test]
+fn test_read_metadata_schema_validation() {
+ let schema = generate_tool_input_schema!(ReadMetadata);
+
+ let result = validate_tool_schema(&schema);
+ assert!(result.is_ok(), "{:?}", result);
+
+ let (name, description) = result.unwrap();
+ assert_eq!(
+ name, "ReadMetadata",
+ "Tool name should match the schemars title"
+ );
+ assert!(
+ description.contains("Retrieve"),
+ "Description should contain expected text"
+ );
+}
+
+#[test]
+fn test_read_content_schema_validation() {
+ let schema = generate_tool_input_schema!(ReadContent);
+
+ let result = validate_tool_schema(&schema);
+ assert!(result.is_ok(), "{:?}", result);
+
+ let (name, description) = result.unwrap();
+ assert_eq!(
+ name, "ReadContent",
+ "Tool name should match the schemars title"
+ );
+ assert!(
+ description.contains("Retrieve"),
+ "Description should contain expected text"
+ );
+}
diff --git a/rust/cloud-storage/documents/src/lib.rs b/rust/cloud-storage/documents/src/lib.rs
index 5e3204d472..4cafcec210 100644
--- a/rust/cloud-storage/documents/src/lib.rs
+++ b/rust/cloud-storage/documents/src/lib.rs
@@ -12,7 +12,7 @@
pub mod domain;
-#[cfg(feature = "inbound")]
+#[cfg(any(feature = "inbound", feature = "ai_tools"))]
pub mod inbound;
#[cfg(feature = "outbound")]
diff --git a/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs b/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs
index 69e0d758df..b6dca69704 100644
--- a/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs
+++ b/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs
@@ -351,4 +351,23 @@ impl DocumentRepo for PgDocumentRepo {
.fetch_all(&self.pool)
.await
}
+
+ #[tracing::instrument(err, skip(self))]
+ async fn get_document_text(&self, document_id: &str) -> Result<String, Self::Err> {
+ let content = sqlx::query!(
+ r#"
+ SELECT
+ d.content
+ FROM
+ "DocumentText" d
+ WHERE
+ d."documentId" = $1
+ "#,
+ document_id
+ )
+ .fetch_one(&self.pool)
+ .await?;
+
+ Ok(content.content)
+ }
}
diff --git a/rust/cloud-storage/entity_access/src/domain/ports.rs b/rust/cloud-storage/entity_access/src/domain/ports.rs
index cf8984d699..e7ad9566c7 100644
--- a/rust/cloud-storage/entity_access/src/domain/ports.rs
+++ b/rust/cloud-storage/entity_access/src/domain/ports.rs
@@ -3,7 +3,9 @@
//! These traits define the contracts that adapters must implement.
use super::models::EntityType;
-use crate::domain::models::{AccessError, AccessLevel, ChannelRoleResult, EntityPermission};
+use crate::domain::models::{
+ AccessError, AccessLevel, ChannelRoleResult, EntityAccessReceipt, EntityPermission,
+};
use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
use std::future::Future;
use uuid::Uuid;
@@ -80,6 +82,16 @@ pub trait AccessRepository: Clone + Send + Sync + 'static {
///
/// This service orchestrates access checks using the repository.
pub trait EntityAccessService: Clone + Send + Sync + 'static {
+ /// Generates an *EntityAccessReceipt* for a given entity and user
+ /// If the user does not have access it will throw an error
+ fn generate_entity_access_receipt(
+ &self,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ user_org_id: Option<i64>,
+ entity_id: &str,
+ entity_type: EntityType,
+ ) -> impl Future<Output = Result<EntityAccessReceipt, AccessError>> + Send;
+
/// Get the access level a user has for an entity.
///
/// Returns `None` if the user has no access to the entity.
diff --git a/rust/cloud-storage/entity_access/src/domain/service.rs b/rust/cloud-storage/entity_access/src/domain/service.rs
index 7dce57bf96..71377b732e 100644
--- a/rust/cloud-storage/entity_access/src/domain/service.rs
+++ b/rust/cloud-storage/entity_access/src/domain/service.rs
@@ -1,10 +1,13 @@
//! Entity access service implementation.
use crate::domain::{
- models::{AccessError, AccessLevel, ChannelRoleResult, EntityPermission, EntityType},
+ models::{
+ AccessError, AccessLevel, ChannelRoleResult, Entity, EntityAccessAuth, EntityAccessReceipt,
+ EntityPermission, EntityType,
+ },
ports::{AccessRepository, EntityAccessService},
};
-use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+use macro_user_id::{cowlike::CowLike, lowercased::Lowercase, user_id::MacroUserId};
use std::str::FromStr;
use uuid::Uuid;
@@ -73,6 +76,28 @@ impl<R> EntityAccessService for EntityAccessServiceImpl<R>
where
R: AccessRepository,
{
+ #[tracing::instrument(err, skip(self))]
+ async fn generate_entity_access_receipt(
+ &self,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ user_org_id: Option<i64>,
+ entity_id: &str,
+ entity_type: EntityType,
+ ) -> Result<EntityAccessReceipt, AccessError> {
+ let entity_permission = self
+ .get_entity_permission(Some(user_id), entity_id, entity_type, user_org_id)
+ .await?;
+
+ Ok(EntityAccessReceipt {
+ auth: EntityAccessAuth::Authenticated(user_id.clone().into_owned()),
+ entity: Entity {
+ entity_id: entity_id.to_string(),
+ entity_type,
+ },
+ entity_permission,
+ })
+ }
+
#[tracing::instrument(err, skip(self))]
async fn get_access_level(
&self,
diff --git a/rust/cloud-storage/entity_access/src/domain/service/test.rs b/rust/cloud-storage/entity_access/src/domain/service/test.rs
index 3d72bc2432..97b449112e 100644
--- a/rust/cloud-storage/entity_access/src/domain/service/test.rs
+++ b/rust/cloud-storage/entity_access/src/domain/service/test.rs
@@ -1,7 +1,7 @@
//! Unit tests for the EntityAccessService.
use super::*;
-use crate::domain::models::ParticipantRole;
+use crate::domain::models::{EntityAccessAuth, ParticipantRole};
use macro_user_id::user_id::MacroUserIdStr;
use std::sync::Arc;
use tokio::sync::Mutex;
@@ -485,3 +485,100 @@ async fn test_check_access_with_none_user_id_and_no_access() {
assert!(matches!(result, Err(AccessError::Unauthorized)));
}
+
+// --- generate_entity_access_receipt tests ---
+
+#[tokio::test]
+async fn test_generate_receipt_document_with_access() {
+ let repo = MockRepo::new().with_document_access(AccessLevel::Edit);
+ let service = EntityAccessServiceImpl::new(repo);
+ let user_id = test_user_id();
+
+ let receipt = service
+ .generate_entity_access_receipt(&user_id, None, "doc-1", EntityType::Document)
+ .await
+ .unwrap();
+
+ assert!(matches!(receipt.auth(), EntityAccessAuth::Authenticated(_)));
+ assert_eq!(receipt.entity().entity_id, "doc-1");
+ assert!(matches!(receipt.entity().entity_type, EntityType::Document));
+ assert!(matches!(
+ receipt.entity_permission(),
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Edit
+ }
+ ));
+}
+
+#[tokio::test]
+async fn test_generate_receipt_document_no_access_returns_unauthorized() {
+ let repo = MockRepo::new();
+ let service = EntityAccessServiceImpl::new(repo);
+ let user_id = test_user_id();
+
+ let result = service
+ .generate_entity_access_receipt(&user_id, None, "doc-1", EntityType::Document)
+ .await;
+
+ assert!(matches!(result, Err(AccessError::Unauthorized)));
+}
+
+#[tokio::test]
+async fn test_generate_receipt_channel_with_role() {
+ let repo = MockRepo::new().with_channel_role(ChannelRoleResult::Role(ParticipantRole::Admin));
+ let service = EntityAccessServiceImpl::new(repo);
+ let user_id = test_user_id();
+
+ let receipt = service
+ .generate_entity_access_receipt(
+ &user_id,
+ None,
+ "11111111-1111-1111-1111-111111111111",
+ EntityType::Channel,
+ )
+ .await
+ .unwrap();
+
+ assert!(matches!(receipt.auth(), EntityAccessAuth::Authenticated(_)));
+ assert_eq!(
+ receipt.entity().entity_id,
+ "11111111-1111-1111-1111-111111111111"
+ );
+ assert!(matches!(
+ receipt.entity_permission(),
+ EntityPermission::ChannelRole {
+ role: ParticipantRole::Admin
+ }
+ ));
+}
+
+#[tokio::test]
+async fn test_generate_receipt_channel_not_found_returns_not_found() {
+ let repo = MockRepo::new().with_channel_role(ChannelRoleResult::NotFound);
+ let service = EntityAccessServiceImpl::new(repo);
+ let user_id = test_user_id();
+
+ let result = service
+ .generate_entity_access_receipt(
+ &user_id,
+ None,
+ "11111111-1111-1111-1111-111111111111",
+ EntityType::Channel,
+ )
+ .await;
+
+ assert!(matches!(result, Err(AccessError::NotFound(_))));
+}
+
+#[tokio::test]
+async fn test_generate_receipt_unsupported_type_returns_bad_request() {
+ let repo = MockRepo::new();
+ let service = EntityAccessServiceImpl::new(repo);
+ let user_id = test_user_id();
+
+ let result = service
+ .generate_entity_access_receipt(&user_id, None, "email-1", EntityType::Email)
+ .await;
+
+ assert!(matches!(result, Err(AccessError::BadRequest(_))));
+}
diff --git a/rust/cloud-storage/model/src/document/mod.rs b/rust/cloud-storage/model/src/document/mod.rs
index 68665440c5..80ac2689a8 100644
--- a/rust/cloud-storage/model/src/document/mod.rs
+++ b/rust/cloud-storage/model/src/document/mod.rs
@@ -4,6 +4,7 @@ pub mod response;
mod test;
use document_sub_type::DocumentSubType;
use macro_user_id::user_id::MacroUserIdStr;
+use schemars::JsonSchema;
use utoipa::ToSchema;
mod file_type;
@@ -142,7 +143,15 @@ pub struct BackfillSearchDocumentInformation {
pub file_type: FileType,
}
#[derive(
- sqlx::FromRow, serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug, Clone, ToSchema,
+ sqlx::FromRow,
+ serde::Serialize,
+ serde::Deserialize,
+ Eq,
+ PartialEq,
+ Debug,
+ Clone,
+ ToSchema,
+ JsonSchema,
)]
#[serde(rename_all = "camelCase")]
pub struct DocumentMetadata {
@@ -155,6 +164,7 @@ pub struct DocumentMetadata {
/// The owner of the document
#[schema(value_type = String)]
#[sqlx(try_from = "String")]
+ #[schemars(with = "String")]
pub owner: MacroUserIdStr<'static>,
/// The name of the document
pub document_name: String,