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 pricing (#3545)

Eric Hayes3a1301cd2773
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 97c00210c9..42e6f09c09 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -6796,6 +6796,7 @@ dependencies = [
"lexical_client",
"macro_auth",
"macro_aws_config",
+ "macro_db_client",
"macro_entrypoint",
"macro_env",
"macro_env_var",
@@ -6807,6 +6808,7 @@ dependencies = [
"readonly_pool",
"redis",
"rmcp",
+ "roles_and_permissions",
"search_service_client",
"secretsmanager_client",
"serde_json",
diff --git a/rust/cloud-storage/chat/src/inbound/http/extractors.rs b/rust/cloud-storage/chat/src/inbound/http/extractors.rs
index 254e59774a..a1c98e974f 100644
--- a/rust/cloud-storage/chat/src/inbound/http/extractors.rs
+++ b/rust/cloud-storage/chat/src/inbound/http/extractors.rs
@@ -8,11 +8,10 @@ use axum::response::IntoResponse;
use model::user::UserContext;
use roles_and_permissions::domain::model::PermissionId;
-/// Axum extractor that resolves the best AI model a user has access to based
-/// on their permissions.
+/// Axum extractor that resolves the AI model a user is entitled to based on
+/// their permissions.
///
-/// The permission hierarchy is: Opus > Sonnet > Haiku. If the user has none
-/// of these permissions the extractor rejects with `402 Payment Required`.
+/// Paid users (any AI write permission) get Opus. Free users get Haiku.
#[derive(Debug)]
pub struct ChatModelAccess(AgentModel);
@@ -29,8 +28,6 @@ pub enum ChatModelAccessRejection {
MissingUserContext,
/// The `UserContext` had no permissions attached.
MissingPermissions,
- /// The user has no AI model permissions (free tier).
- NoModelAccess,
}
impl IntoResponse for ChatModelAccessRejection {
@@ -44,11 +41,6 @@ impl IntoResponse for ChatModelAccessRejection {
"missing user permissions",
)
.into_response(),
- Self::NoModelAccess => (
- StatusCode::PAYMENT_REQUIRED,
- "AI features require a paid subscription",
- )
- .into_response(),
}
}
}
@@ -67,14 +59,14 @@ impl<S: Send + Sync> FromRequestParts<S> for ChatModelAccess {
.as_ref()
.ok_or(ChatModelAccessRejection::MissingPermissions)?;
- let model = if permissions.contains(&PermissionId::WriteOpus.to_string()) {
+ let is_paid = permissions.contains(&PermissionId::WriteOpus.to_string())
+ || permissions.contains(&PermissionId::WriteSonnet.to_string())
+ || permissions.contains(&PermissionId::WriteHaiku.to_string());
+
+ let model = if is_paid {
AgentModel::Opus4_7
- } else if permissions.contains(&PermissionId::WriteSonnet.to_string()) {
- AgentModel::Sonnet4_6
- } else if permissions.contains(&PermissionId::WriteHaiku.to_string()) {
- AgentModel::Haiku4_5
} else {
- return Err(ChatModelAccessRejection::NoModelAccess);
+ AgentModel::Haiku4_5
};
Ok(ChatModelAccess(model))
diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/mod.rs
index a909b8d234..937b14b937 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/mod.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/mod.rs
@@ -179,10 +179,12 @@ async fn send_chat_message_inner(
// Determine chat_id - use provided or we'll create a new chat
let requested_chat_id = request.chat_id.clone().unwrap_or_default();
+ let model = model_access.model();
+
// Try to get the chat first - if it doesn't exist or no chat_id provided, create it
let (chat, actual_chat_id) = if requested_chat_id.is_empty() {
// No chat_id provided - create a new chat
- create_new_chat(&ctx, &user_id, request.model, &stream_id).await?
+ create_new_chat(&ctx, &user_id, model, &stream_id).await?
} else {
match get_chat(&ctx, &requested_chat_id, user_id.0.as_ref()).await {
Ok(chat) => {
@@ -221,19 +223,17 @@ async fn send_chat_message_inner(
requested_chat_id = %requested_chat_id,
"Chat not found, creating new chat"
);
- create_new_chat(&ctx, &user_id, request.model, &stream_id).await?
+ create_new_chat(&ctx, &user_id, model, &stream_id).await?
}
}
};
- let model = model_access.model();
-
// Convert HTTP request to internal payload for existing functions
let payload = SendChatMessagePayload {
stream_id: stream_id.clone(),
content: request.content.clone(),
chat_id: actual_chat_id.clone(),
- model: request.model,
+ model,
additional_instructions: request.additional_instructions.clone(),
attachments: request.attachments.clone(),
toolset: request.toolset.clone(),
diff --git a/rust/cloud-storage/mcp_service/Cargo.toml b/rust/cloud-storage/mcp_service/Cargo.toml
index 0336383a85..d0dcac20f3 100644
--- a/rust/cloud-storage/mcp_service/Cargo.toml
+++ b/rust/cloud-storage/mcp_service/Cargo.toml
@@ -27,6 +27,7 @@ http = { workspace = true }
lexical_client = { path = "../lexical_client" }
mcp_auth_proxy = { path = "../mcp_auth_proxy" }
macro_auth = { path = "../macro_auth" }
+macro_db_client = { path = "../macro_db_client" }
macro_aws_config = { path = "../macro_aws_config", features = ["s3"] }
macro_entrypoint = { path = "../macro_entrypoint" }
macro_env = { path = "../macro_env" }
@@ -41,6 +42,7 @@ notification = { path = "../notification", features = ["ai_tool"] }
properties = { path = "../properties", features = ["ai_tools"] }
readonly_pool = { path = "../readonly_pool" }
redis = { workspace = true, features = ["aio", "tokio-comp"] }
+roles_and_permissions = { path = "../roles_and_permissions" }
rmcp = { workspace = true, features = ["transport-streamable-http-server"] }
search_service_client = { path = "../search_service_client" }
secretsmanager_client = { path = "../secretsmanager_client" }
diff --git a/rust/cloud-storage/mcp_service/src/context.rs b/rust/cloud-storage/mcp_service/src/context.rs
index fd225005ea..ca675ad6df 100644
--- a/rust/cloud-storage/mcp_service/src/context.rs
+++ b/rust/cloud-storage/mcp_service/src/context.rs
@@ -70,6 +70,7 @@ pub struct McpContext {
pub tool_context: ToolServiceContext,
pub auth_proxy: McpAuthProxyServiceImpl<RedisInflightAuth>,
pub mcp_public_host: String,
+ pub db: PgPool,
}
pub async fn build_context() -> anyhow::Result<McpContext> {
@@ -132,6 +133,7 @@ pub async fn build_context() -> anyhow::Result<McpContext> {
tool_context,
auth_proxy,
mcp_public_host,
+ db,
})
}
diff --git a/rust/cloud-storage/mcp_service/src/main.rs b/rust/cloud-storage/mcp_service/src/main.rs
index 07ef71b431..32c493ec25 100644
--- a/rust/cloud-storage/mcp_service/src/main.rs
+++ b/rust/cloud-storage/mcp_service/src/main.rs
@@ -34,6 +34,7 @@ async fn main() -> anyhow::Result<()> {
Ok(AuthenticatedToolService::new(
tools.toolset,
context.tool_context.clone(),
+ context.db.clone(),
))
},
Arc::new(LocalSessionManager::default()),
diff --git a/rust/cloud-storage/mcp_service/src/tool_service.rs b/rust/cloud-storage/mcp_service/src/tool_service.rs
index dc21ed03aa..955597bd2a 100644
--- a/rust/cloud-storage/mcp_service/src/tool_service.rs
+++ b/rust/cloud-storage/mcp_service/src/tool_service.rs
@@ -6,19 +6,30 @@ use rmcp::{
Content, ListToolsResult, PaginatedRequestParams, ServerCapabilities, ServerInfo, Tool,
},
};
+use roles_and_permissions::domain::model::PermissionId;
+use sqlx::PgPool;
use std::sync::Arc;
/// MCP server handler that extracts authenticated user identity from HTTP
/// request parts injected by rmcp's `StreamableHttpService`.
+#[allow(
+ dead_code,
+ reason = "fields used via ServerHandler trait impl dispatched by rmcp"
+)]
pub struct AuthenticatedToolService<Context> {
toolset: Arc<AsyncToolCollection<Context>>,
context: Context,
+ db: PgPool,
}
impl<Context> AuthenticatedToolService<Context> {
/// Creates a new authenticated tool service.
- pub fn new(toolset: Arc<AsyncToolCollection<Context>>, context: Context) -> Self {
- Self { toolset, context }
+ pub fn new(toolset: Arc<AsyncToolCollection<Context>>, context: Context, db: PgPool) -> Self {
+ Self {
+ toolset,
+ context,
+ db,
+ }
}
fn tool_definitions(&self) -> Vec<Tool> {
@@ -45,6 +56,35 @@ impl<Context> AuthenticatedToolService<Context> {
rmcp::ErrorData::internal_error("missing user identity — is auth configured?", None)
})
}
+
+ async fn require_paid_subscription(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ ) -> Result<(), rmcp::ErrorData> {
+ let permissions = macro_db_client::user::get_permissions::get_user_permissions(
+ &self.db,
+ user_id.0.as_ref(),
+ )
+ .await
+ .map_err(|e| {
+ tracing::error!(error=?e, "failed to check user permissions for MCP access");
+ rmcp::ErrorData::internal_error("failed to check permissions", None)
+ })?;
+
+ let is_paid = permissions.contains(&PermissionId::WriteOpus.to_string())
+ || permissions.contains(&PermissionId::WriteSonnet.to_string())
+ || permissions.contains(&PermissionId::WriteHaiku.to_string());
+
+ if !is_paid {
+ return Err(rmcp::ErrorData::new(
+ rmcp::model::ErrorCode::INVALID_REQUEST,
+ "MCP access requires a paid subscription",
+ None,
+ ));
+ }
+
+ Ok(())
+ }
}
#[cfg(test)]
@@ -78,8 +118,11 @@ where
async fn list_tools(
&self,
_request: Option<PaginatedRequestParams>,
- _context: rmcp::service::RequestContext<rmcp::RoleServer>,
+ context: rmcp::service::RequestContext<rmcp::RoleServer>,
) -> Result<ListToolsResult, rmcp::ErrorData> {
+ let user_id = Self::authenticated_user_id(&context.extensions)?;
+ self.require_paid_subscription(&user_id).await?;
+
Ok(ListToolsResult {
tools: self.tool_definitions(),
..Default::default()
@@ -92,6 +135,7 @@ where
context: rmcp::service::RequestContext<rmcp::RoleServer>,
) -> Result<rmcp::model::CallToolResult, rmcp::ErrorData> {
let user_id = Self::authenticated_user_id(&context.extensions)?;
+ self.require_paid_subscription(&user_id).await?;
let request_context = RequestContext { user_id };
diff --git a/rust/cloud-storage/mcp_service/src/tool_service/test.rs b/rust/cloud-storage/mcp_service/src/tool_service/test.rs
index d89da6fdc3..c8094fd855 100644
--- a/rust/cloud-storage/mcp_service/src/tool_service/test.rs
+++ b/rust/cloud-storage/mcp_service/src/tool_service/test.rs
@@ -1,13 +1,17 @@
use super::*;
use ai_toolset::AsyncToolCollection;
use rmcp::{handler::server::ServerHandler, model::ErrorCode};
+use sqlx::postgres::PgPoolOptions;
fn empty_service() -> AuthenticatedToolService<()> {
- AuthenticatedToolService::new(Arc::new(AsyncToolCollection::new()), ())
+ let db = PgPoolOptions::new()
+ .connect_lazy("postgres://localhost/unused")
+ .expect("lazy pool creation should not fail");
+ AuthenticatedToolService::new(Arc::new(AsyncToolCollection::new()), (), db)
}
-#[test]
-fn server_info_advertises_macro_tools() {
+#[tokio::test]
+async fn server_info_advertises_macro_tools() {
let info = empty_service().get_info();
assert_eq!(info.server_info.name, "macro-tools");
@@ -22,8 +26,8 @@ fn server_info_advertises_macro_tools() {
assert!(info.capabilities.tools.is_some());
}
-#[test]
-fn server_instructions_describe_available_workflows() {
+#[tokio::test]
+async fn server_instructions_describe_available_workflows() {
let instructions = empty_service()
.get_info()
.instructions
@@ -46,8 +50,8 @@ fn server_instructions_describe_available_workflows() {
}
}
-#[test]
-fn empty_toolset_lists_no_tools() {
+#[tokio::test]
+async fn empty_toolset_lists_no_tools() {
assert!(empty_service().tool_definitions().is_empty());
}