feat(cli): migrate CLI to native Rust binary

This commit is contained in:
t8y2 committed 2026-07-18 22:29:29 +08:00
1 parent fa5579a3f1
commit 4bcf618162
47 files changed
+2369 -1255

No files matched your search

-1
View File
@@ -13,7 +13,6 @@ async-trait = "0.1"
dbx-core = { path = "../dbx-core", default-features = false }
rmcp = { version = "2.2.0", features = ["client", "transport-io"] }
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
json5 = "0.4"
schemars = "1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
+296 -72
View File
@@ -53,6 +53,17 @@ pub trait DbxBackend: Send + Sync {
arguments: Value,
permissions: AgentSqlPermissions,
) -> ToolResult;
async fn execute_query(
&self,
connection: &ConnectionConfig,
database: &str,
sql: &str,
max_rows: Option<usize>,
timeout_secs: Option<u64>,
) -> Result<dbx_core::db::QueryResult, String> {
let _ = (connection, database, sql, max_rows, timeout_secs);
Err("SQL queries are not supported by this backend.".to_string())
}
async fn save_connections(&self, connections: &[ConnectionConfig]) -> Result<(), String>;
async fn list_tables(
&self,
@@ -88,7 +99,7 @@ pub trait DbxBackend: Send + Sync {
connection: &ConnectionConfig,
database: &str,
command: &MongoCommand,
) -> Result<String, String> {
) -> Result<dbx_core::db::QueryResult, String> {
let _ = (connection, database, command);
Err("MongoDB shell commands are not supported by this backend.".to_string())
}
@@ -255,6 +266,26 @@ impl DbxBackend for LocalBackend {
agent_tools::execute_tool(&call, &self.state, &connection.id, database, &connection.db_type, permissions).await
}
async fn execute_query(
&self,
connection: &ConnectionConfig,
database: &str,
sql: &str,
max_rows: Option<usize>,
timeout_secs: Option<u64>,
) -> Result<dbx_core::db::QueryResult, String> {
dbx_core::query::execute_sql_statement_with_options(
&self.state,
&connection.id,
database,
sql,
None,
None,
dbx_core::query::QueryExecutionOptions { max_rows, timeout_secs, ..Default::default() },
)
.await
}
async fn save_connections(&self, connections: &[ConnectionConfig]) -> Result<(), String> {
self.state.storage.save_connections(connections).await?;
*self.state.configs.write().await =
@@ -303,14 +334,15 @@ impl DbxBackend for LocalBackend {
connection: &ConnectionConfig,
database: &str,
command: &MongoCommand,
) -> Result<String, String> {
) -> Result<dbx_core::db::QueryResult, String> {
use dbx_core::mongo_ops;
let connection_id = &connection.id;
match command {
MongoCommand::Version => mongo_ops::mongo_server_version_core(&self.state, connection_id, database)
.await
.map(|version| format!("| version |\n| --- |\n| {} |\n\n1 row(s)", escape_markdown_cell(&version))),
.map(|version| scalar_query_result("version", Value::String(version))),
MongoCommand::Use { database } => Ok(scalar_query_result("database", Value::String(database.clone()))),
MongoCommand::Find { collection, filter, projection, sort, skip, limit } => {
let result = mongo_ops::mongo_find_documents_core(
&self.state,
@@ -324,7 +356,20 @@ impl DbxBackend for LocalBackend {
sort.as_deref(),
)
.await?;
Ok(format_mongo_documents(&result.documents))
Ok(mongo_documents_query_result(result.documents))
}
MongoCommand::FindOne { collection, filter, projection, options } => {
let result = mongo_ops::mongo_find_one_core(
&self.state,
connection_id,
database,
collection,
Some(filter),
projection.as_deref(),
options.as_deref(),
)
.await?;
Ok(mongo_documents_query_result(result.documents))
}
MongoCommand::Count { collection, filter, accurate } => {
let mode = if *accurate { "accurate" } else { "legacy" };
@@ -337,7 +382,7 @@ impl DbxBackend for LocalBackend {
Some(mode),
)
.await?;
Ok(format!("| count |\n| --- |\n| {total} |\n\n1 row(s)"))
Ok(scalar_query_result("count", Value::from(total)))
}
MongoCommand::Aggregate { collection, pipeline, options } => {
let result = mongo_ops::mongo_aggregate_documents_core(
@@ -350,7 +395,7 @@ impl DbxBackend for LocalBackend {
options.as_deref(),
)
.await?;
Ok(format_mongo_documents(&result.documents))
Ok(mongo_documents_query_result(result.documents))
}
MongoCommand::Distinct { collection, field, filter } => {
let result = mongo_ops::mongo_distinct_core(
@@ -362,7 +407,7 @@ impl DbxBackend for LocalBackend {
filter.as_deref(),
)
.await?;
Ok(format_mongo_documents(&result.documents))
Ok(mongo_documents_query_result(result.documents))
}
MongoCommand::GetIndexes { collection } => {
let result = mongo_ops::mongo_aggregate_documents_core(
@@ -375,7 +420,7 @@ impl DbxBackend for LocalBackend {
None,
)
.await?;
Ok(format_mongo_documents(&result.documents))
Ok(mongo_documents_query_result(result.documents))
}
MongoCommand::CollectionStats { collection, metric, scale } => {
let stats = mongo_ops::mongo_collection_stats_core(
@@ -388,7 +433,7 @@ impl DbxBackend for LocalBackend {
.await?;
let value = serde_json::to_value(stats).map_err(|error| error.to_string())?;
if metric == "stats" {
Ok(serde_json::to_string_pretty(&value).unwrap_or_else(|_| value.to_string()))
Ok(mongo_documents_query_result(vec![value]))
} else {
let key = match metric.as_str() {
"dataSize" => "size",
@@ -397,14 +442,14 @@ impl DbxBackend for LocalBackend {
_ => metric,
};
let metric_value = value.get(key).cloned().unwrap_or(Value::Null);
Ok(format!("| {metric} |\n| --- |\n| {} |\n\n1 row(s)", format_query_cell(&metric_value)))
Ok(scalar_query_result(metric, metric_value))
}
}
MongoCommand::Insert { collection, documents } => {
let affected =
mongo_ops::mongo_insert_documents_core(&self.state, connection_id, database, collection, documents)
.await?;
Ok(format!("Query executed. {affected} row(s) affected."))
Ok(affected_query_result(affected))
}
MongoCommand::Update { collection, filter, update, options, many } => {
let affected = mongo_ops::mongo_update_documents_core(
@@ -418,7 +463,7 @@ impl DbxBackend for LocalBackend {
options.as_deref(),
)
.await?;
Ok(format!("Query executed. {affected} row(s) affected."))
Ok(affected_query_result(affected))
}
MongoCommand::Delete { collection, filter, many } => {
let affected = mongo_ops::mongo_delete_documents_core(
@@ -430,7 +475,7 @@ impl DbxBackend for LocalBackend {
*many,
)
.await?;
Ok(format!("Query executed. {affected} row(s) affected."))
Ok(affected_query_result(affected))
}
MongoCommand::CreateIndex { collection, keys, options } => {
let name = mongo_ops::mongo_create_index_core(
@@ -442,7 +487,7 @@ impl DbxBackend for LocalBackend {
options.as_deref(),
)
.await?;
Ok(format!("| name |\n| --- |\n| {} |\n\n1 row(s)", escape_markdown_cell(&name)))
Ok(scalar_query_result("name", Value::String(name)))
}
MongoCommand::DropIndexes { collection, indexes, single } => {
let result = mongo_ops::mongo_drop_indexes_core(
@@ -454,11 +499,54 @@ impl DbxBackend for LocalBackend {
*single,
)
.await?;
Ok(format!("Query executed. {} row(s) affected.", result.affected_rows))
let rows = result.dropped_names.into_iter().map(|name| vec![Value::String(name)]).collect::<Vec<_>>();
Ok(query_result(
if rows.is_empty() { Vec::new() } else { vec!["name".to_string()] },
rows,
result.affected_rows,
))
}
MongoCommand::DropCollection { collection } => {
mongo_ops::mongo_drop_collection_core(&self.state, connection_id, database, collection).await?;
Ok("Query executed. 1 row(s) affected.".to_string())
Ok(affected_query_result(1))
}
MongoCommand::FindOneAndUpdate { collection, filter, update, options } => {
let result = mongo_ops::mongo_find_one_and_update_core(
&self.state,
connection_id,
database,
collection,
filter,
update,
options.as_deref(),
)
.await?;
Ok(mongo_documents_query_result(result.documents))
}
MongoCommand::FindOneAndReplace { collection, filter, replacement, options } => {
let result = mongo_ops::mongo_find_one_and_replace_core(
&self.state,
connection_id,
database,
collection,
filter,
replacement,
options.as_deref(),
)
.await?;
Ok(mongo_documents_query_result(result.documents))
}
MongoCommand::FindOneAndDelete { collection, filter, options } => {
let result = mongo_ops::mongo_find_one_and_delete_core(
&self.state,
connection_id,
database,
collection,
filter,
options.as_deref(),
)
.await?;
Ok(mongo_documents_query_result(result.documents))
}
}
}
@@ -532,6 +620,29 @@ impl DbxBackend for WebBackend {
}
}
async fn execute_query(
&self,
connection: &ConnectionConfig,
database: &str,
sql: &str,
_max_rows: Option<usize>,
_timeout_secs: Option<u64>,
) -> Result<dbx_core::db::QueryResult, String> {
if connection.db_type == DatabaseType::MongoDb {
return Err("MongoDB shell commands in DBX Web mode are not implemented by the Rust CLI yet.".to_string());
}
self.ensure_connected(connection).await?;
self.request(
reqwest::Method::POST,
"/api/query/execute",
Some(json!({ "connectionId": connection.id, "database": database, "sql": sql })),
)
.await?
.json()
.await
.map_err(|error| format!("Invalid query response: {error}"))
}
async fn save_connections(&self, _connections: &[ConnectionConfig]) -> Result<(), String> {
Err("Connection changes are unavailable in DBX Web mode.".to_string())
}
@@ -665,7 +776,7 @@ impl DbxBackend for WebBackend {
connection: &ConnectionConfig,
database: &str,
command: &MongoCommand,
) -> Result<String, String> {
) -> Result<dbx_core::db::QueryResult, String> {
self.ensure_connected(connection).await?;
let connection_id = &connection.id;
match command {
@@ -680,8 +791,9 @@ impl DbxBackend for WebBackend {
.json()
.await
.map_err(|error| format!("Invalid MongoDB version response: {error}"))?;
Ok(format!("| version |\n| --- |\n| {} |\n\n1 row(s)", escape_markdown_cell(&version)))
Ok(scalar_query_result("version", Value::String(version)))
}
MongoCommand::Use { database } => Ok(scalar_query_result("database", Value::String(database.clone()))),
MongoCommand::Find { collection, filter, projection, sort, skip, limit } => {
let result = self
.request(
@@ -702,7 +814,27 @@ impl DbxBackend for WebBackend {
.json::<WebMongoDocuments>()
.await
.map_err(|error| format!("Invalid MongoDB find response: {error}"))?;
Ok(format_mongo_documents(&result.documents))
Ok(mongo_documents_query_result(result.documents))
}
MongoCommand::FindOne { collection, filter, projection, options } => {
let result = self
.request(
reqwest::Method::POST,
"/api/mongo/find-one",
Some(json!({
"connectionId": connection_id,
"database": database,
"collection": collection,
"filter": filter,
"projection": projection,
"options": options,
})),
)
.await?
.json::<WebMongoDocuments>()
.await
.map_err(|error| format!("Invalid MongoDB findOne response: {error}"))?;
Ok(mongo_documents_query_result(result.documents))
}
MongoCommand::Count { collection, filter, accurate } => {
let total: u64 = self
@@ -721,7 +853,7 @@ impl DbxBackend for WebBackend {
.json()
.await
.map_err(|error| format!("Invalid MongoDB count response: {error}"))?;
Ok(format!("| count |\n| --- |\n| {total} |\n\n1 row(s)"))
Ok(scalar_query_result("count", Value::from(total)))
}
MongoCommand::Aggregate { collection, pipeline, options } => {
let result = self
@@ -741,7 +873,7 @@ impl DbxBackend for WebBackend {
.json::<WebMongoDocuments>()
.await
.map_err(|error| format!("Invalid MongoDB aggregate response: {error}"))?;
Ok(format_mongo_documents(&result.documents))
Ok(mongo_documents_query_result(result.documents))
}
MongoCommand::Distinct { collection, field, filter } => {
let result = self
@@ -760,7 +892,7 @@ impl DbxBackend for WebBackend {
.json::<WebMongoDocuments>()
.await
.map_err(|error| format!("Invalid MongoDB distinct response: {error}"))?;
Ok(format_mongo_documents(&result.documents))
Ok(mongo_documents_query_result(result.documents))
}
MongoCommand::GetIndexes { collection } => {
let result = self
@@ -779,7 +911,7 @@ impl DbxBackend for WebBackend {
.json::<WebMongoDocuments>()
.await
.map_err(|error| format!("Invalid MongoDB indexes response: {error}"))?;
Ok(format_mongo_documents(&result.documents))
Ok(mongo_documents_query_result(result.documents))
}
MongoCommand::CollectionStats { collection, metric, scale } => {
let value: Value = self
@@ -798,7 +930,7 @@ impl DbxBackend for WebBackend {
.await
.map_err(|error| format!("Invalid MongoDB stats response: {error}"))?;
if metric == "stats" {
Ok(serde_json::to_string_pretty(&value).unwrap_or_else(|_| value.to_string()))
Ok(mongo_documents_query_result(vec![value]))
} else {
let key = match metric.as_str() {
"dataSize" => "size",
@@ -807,7 +939,7 @@ impl DbxBackend for WebBackend {
_ => metric,
};
let metric_value = value.get(key).cloned().unwrap_or(Value::Null);
Ok(format!("| {metric} |\n| --- |\n| {} |\n\n1 row(s)", format_query_cell(&metric_value)))
Ok(scalar_query_result(metric, metric_value))
}
}
MongoCommand::Insert { collection, documents } => {
@@ -826,7 +958,7 @@ impl DbxBackend for WebBackend {
.json()
.await
.map_err(|error| format!("Invalid MongoDB insert response: {error}"))?;
Ok(format_affected_rows(&value))
Ok(affected_query_result(affected_rows_from_value(&value)))
}
MongoCommand::Update { collection, filter, update, options, many } => {
let value: Value = self
@@ -847,7 +979,7 @@ impl DbxBackend for WebBackend {
.json()
.await
.map_err(|error| format!("Invalid MongoDB update response: {error}"))?;
Ok(format_affected_rows(&value))
Ok(affected_query_result(affected_rows_from_value(&value)))
}
MongoCommand::Delete { collection, filter, many } => {
let value: Value = self
@@ -866,7 +998,7 @@ impl DbxBackend for WebBackend {
.json()
.await
.map_err(|error| format!("Invalid MongoDB delete response: {error}"))?;
Ok(format_affected_rows(&value))
Ok(affected_query_result(affected_rows_from_value(&value)))
}
MongoCommand::CreateIndex { collection, keys, options } => {
let value: Value = self
@@ -885,9 +1017,9 @@ impl DbxBackend for WebBackend {
.json()
.await
.map_err(|error| format!("Invalid MongoDB create index response: {error}"))?;
Ok(format!(
"| name |\n| --- |\n| {} |\n\n1 row(s)",
escape_markdown_cell(value.get("name").and_then(Value::as_str).unwrap_or(""))
Ok(scalar_query_result(
"name",
Value::String(value.get("name").and_then(Value::as_str).unwrap_or("").to_string()),
))
}
MongoCommand::DropIndexes { collection, indexes, single } => {
@@ -907,7 +1039,20 @@ impl DbxBackend for WebBackend {
.json()
.await
.map_err(|error| format!("Invalid MongoDB drop indexes response: {error}"))?;
Ok(format_affected_rows(&value))
let dropped_names = value
.get("dropped_names")
.or_else(|| value.get("droppedNames"))
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(Value::as_str)
.map(|name| vec![Value::String(name.to_string())])
.collect::<Vec<_>>();
Ok(query_result(
if dropped_names.is_empty() { Vec::new() } else { vec!["name".to_string()] },
dropped_names,
affected_rows_from_value(&value),
))
}
MongoCommand::DropCollection { collection } => {
self.request(
@@ -916,7 +1061,66 @@ impl DbxBackend for WebBackend {
Some(json!({ "connectionId": connection_id, "database": database, "collection": collection })),
)
.await?;
Ok("Query executed. 1 row(s) affected.".to_string())
Ok(affected_query_result(1))
}
MongoCommand::FindOneAndUpdate { collection, filter, update, options } => {
let result = self
.request(
reqwest::Method::POST,
"/api/mongo/find-one-and-update",
Some(json!({
"connectionId": connection_id,
"database": database,
"collection": collection,
"filterJson": filter,
"updateJson": update,
"optionsJson": options,
})),
)
.await?
.json::<WebMongoDocuments>()
.await
.map_err(|error| format!("Invalid MongoDB findOneAndUpdate response: {error}"))?;
Ok(mongo_documents_query_result(result.documents))
}
MongoCommand::FindOneAndReplace { collection, filter, replacement, options } => {
let result = self
.request(
reqwest::Method::POST,
"/api/mongo/find-one-and-replace",
Some(json!({
"connectionId": connection_id,
"database": database,
"collection": collection,
"filterJson": filter,
"replacementJson": replacement,
"optionsJson": options,
})),
)
.await?
.json::<WebMongoDocuments>()
.await
.map_err(|error| format!("Invalid MongoDB findOneAndReplace response: {error}"))?;
Ok(mongo_documents_query_result(result.documents))
}
MongoCommand::FindOneAndDelete { collection, filter, options } => {
let result = self
.request(
reqwest::Method::POST,
"/api/mongo/find-one-and-delete",
Some(json!({
"connectionId": connection_id,
"database": database,
"collection": collection,
"filterJson": filter,
"optionsJson": options,
})),
)
.await?
.json::<WebMongoDocuments>()
.await
.map_err(|error| format!("Invalid MongoDB findOneAndDelete response: {error}"))?;
Ok(mongo_documents_query_result(result.documents))
}
}
}
@@ -938,7 +1142,7 @@ fn url_encode(value: &str) -> String {
url::form_urlencoded::byte_serialize(value.as_bytes()).collect()
}
fn format_query_result(result: &dbx_core::db::QueryResult, max_rows: usize) -> String {
pub(crate) fn format_query_result(result: &dbx_core::db::QueryResult, max_rows: usize) -> String {
if result.columns.is_empty() {
return format!("Query executed. {} row(s) affected.", result.affected_rows);
}
@@ -953,6 +1157,64 @@ fn format_query_result(result: &dbx_core::db::QueryResult, max_rows: usize) -> S
output
}
fn query_result(columns: Vec<String>, rows: Vec<Vec<Value>>, affected_rows: u64) -> dbx_core::db::QueryResult {
dbx_core::db::QueryResult {
columns,
column_types: Vec::new(),
column_sortables: Vec::new(),
rows,
affected_rows,
execution_time_ms: 0,
truncated: false,
session_id: None,
has_more: false,
}
}
fn scalar_query_result(column: impl Into<String>, value: Value) -> dbx_core::db::QueryResult {
query_result(vec![column.into()], vec![vec![value]], 0)
}
fn affected_query_result(affected_rows: u64) -> dbx_core::db::QueryResult {
query_result(Vec::new(), Vec::new(), affected_rows)
}
fn mongo_documents_query_result(documents: Vec<Value>) -> dbx_core::db::QueryResult {
if documents.is_empty() {
return query_result(Vec::new(), Vec::new(), 0);
}
let mut columns = std::collections::BTreeSet::new();
for document in &documents {
if let Some(object) = document.as_object() {
columns.extend(object.keys().cloned());
} else {
columns.insert("value".to_string());
}
}
let columns = columns.into_iter().collect::<Vec<_>>();
let rows = documents
.into_iter()
.map(|document| {
columns
.iter()
.map(|column| {
document
.as_object()
.and_then(|object| object.get(column))
.cloned()
.or_else(|| (column == "value").then(|| document.clone()))
.unwrap_or(Value::Null)
})
.collect()
})
.collect();
query_result(columns, rows, 0)
}
fn affected_rows_from_value(value: &Value) -> u64 {
value.get("affected_rows").or_else(|| value.get("affectedRows")).and_then(Value::as_u64).unwrap_or(0)
}
fn format_query_cell(value: &Value) -> String {
match value {
Value::Null => "NULL".to_string(),
@@ -962,44 +1224,6 @@ fn format_query_cell(value: &Value) -> String {
}
}
fn format_mongo_documents(documents: &[Value]) -> String {
if documents.is_empty() {
return "Query returned 0 rows.".to_string();
}
let mut headers = std::collections::BTreeSet::new();
for document in documents {
if let Some(object) = document.as_object() {
headers.extend(object.keys().cloned());
} else {
headers.insert("value".to_string());
}
}
let headers = headers.into_iter().collect::<Vec<_>>();
let rows = documents
.iter()
.map(|document| {
headers
.iter()
.map(|header| {
document
.as_object()
.and_then(|object| object.get(header))
.or_else(|| (header == "value").then_some(document))
.map(format_query_cell)
.unwrap_or_else(|| "NULL".to_string())
})
.collect::<Vec<_>>()
})
.collect::<Vec<_>>();
format!("{}\n\n{} row(s)", markdown_table(&headers, &rows), documents.len())
}
fn format_affected_rows(value: &Value) -> String {
let affected =
value.get("affected_rows").or_else(|| value.get("affectedRows")).and_then(Value::as_u64).unwrap_or(0);
format!("Query executed. {affected} row(s) affected.")
}
fn markdown_table(headers: &[String], rows: &[Vec<String>]) -> String {
let mut output = format!(
"| {} |\n| {} |",
+1 -1
View File
@@ -1,7 +1,7 @@
pub mod backend;
pub mod mongo;
pub mod paths;
pub mod server;
pub use backend::{ConnectionSummary, DbxBackend, LocalBackend, WebBackend};
pub use dbx_core::mongo_shell as mongo;
pub use server::{DbxMcpServer, McpScope};
-491
View File
@@ -1,491 +0,0 @@
use serde_json::Value;
#[derive(Debug, Clone, PartialEq)]
pub enum MongoCommand {
Version,
Find { collection: String, filter: String, projection: Option<String>, sort: Option<String>, skip: u64, limit: i64 },
Count { collection: String, filter: String, accurate: bool },
Aggregate { collection: String, pipeline: String, options: Option<String> },
Distinct { collection: String, field: String, filter: Option<String> },
GetIndexes { collection: String },
CollectionStats { collection: String, metric: String, scale: Option<serde_json::Number> },
Insert { collection: String, documents: String },
Update { collection: String, filter: String, update: String, options: Option<String>, many: bool },
Delete { collection: String, filter: String, many: bool },
CreateIndex { collection: String, keys: String, options: Option<String> },
DropIndexes { collection: String, indexes: Option<String>, single: bool },
DropCollection { collection: String },
}
impl MongoCommand {
pub fn is_mutating(&self) -> bool {
matches!(
self,
Self::Insert { .. }
| Self::Update { .. }
| Self::Delete { .. }
| Self::CreateIndex { .. }
| Self::DropIndexes { .. }
| Self::DropCollection { .. }
) || matches!(self, Self::Aggregate { pipeline, .. } if aggregate_writes(pipeline))
}
pub fn is_dangerous(&self) -> bool {
matches!(self, Self::DropCollection { .. })
|| matches!(self, Self::DropIndexes { indexes: None, single: false, .. })
|| matches!(self, Self::Aggregate { pipeline, .. } if aggregate_writes(pipeline))
}
pub fn has_empty_filter(&self) -> bool {
match self {
Self::Update { filter, .. } | Self::Delete { filter, .. } => is_empty_object(filter),
_ => false,
}
}
}
pub fn parse(input: &str) -> Result<MongoCommand, String> {
let source = input.trim().trim_end_matches(';').trim();
if source.eq_ignore_ascii_case("db.version()") {
return Ok(MongoCommand::Version);
}
let (collection, prefix_end) = parse_collection_prefix(source)?;
if let Some((args, tail)) = method_call(source, prefix_end, "find") {
let filter = normalized_json(args.first().map(String::as_str).unwrap_or("{}"))?;
let projection =
if args.get(1).is_some_and(|arg| !arg.trim().is_empty()) { Some(normalized_json(&args[1])?) } else { None };
if args.len() > 2 {
return Err("MongoDB find() accepts at most filter and projection arguments.".to_string());
}
let mut sort = None;
let mut skip = 0;
let mut limit = 100;
for (name, call_args) in chained_calls(&tail)? {
match name.as_str() {
"sort" => sort = Some(normalized_json(call_args.first().map(String::as_str).unwrap_or("{}"))?),
"skip" => skip = parse_integer(&call_args, "skip")? as u64,
"limit" => limit = parse_integer(&call_args, "limit")?,
"count" if call_args.is_empty() => {
return Ok(MongoCommand::Count { collection, filter, accurate: false });
}
_ => return Err(format!("Unsupported MongoDB find() chain: {name}()")),
}
}
return Ok(MongoCommand::Find { collection, filter, projection, sort, skip, limit });
}
for (method, accurate) in [("countDocuments", true), ("count", false)] {
if let Some((args, tail)) = method_call(source, prefix_end, method) {
if !tail.is_empty() || args.len() > 1 {
return Err(format!("Invalid MongoDB {method}() command."));
}
return Ok(MongoCommand::Count {
collection,
filter: normalized_json(args.first().map(String::as_str).unwrap_or("{}"))?,
accurate,
});
}
}
if let Some((args, tail)) = method_call(source, prefix_end, "aggregate") {
if !tail.is_empty() || !(1..=2).contains(&args.len()) {
return Err("Invalid MongoDB aggregate() command.".to_string());
}
let pipeline = normalized_json(&args[0])?;
if !parse_json_value(&pipeline).is_some_and(|value| value.is_array()) {
return Err("MongoDB aggregate() requires a pipeline array.".to_string());
}
let options = args.get(1).filter(|arg| !arg.trim().is_empty()).map(|arg| normalized_json(arg)).transpose()?;
return Ok(MongoCommand::Aggregate { collection, pipeline, options });
}
if let Some((args, tail)) = method_call(source, prefix_end, "distinct") {
if !tail.is_empty() || !(1..=2).contains(&args.len()) {
return Err("Invalid MongoDB distinct() command.".to_string());
}
let field = parse_string_arg(&args[0])?;
let filter = args.get(1).filter(|arg| !arg.trim().is_empty()).map(|arg| normalized_json(arg)).transpose()?;
return Ok(MongoCommand::Distinct { collection, field, filter });
}
if let Some((args, tail)) = method_call(source, prefix_end, "getIndexes") {
if !tail.is_empty() || !args.is_empty() {
return Err("Invalid MongoDB getIndexes() command.".to_string());
}
return Ok(MongoCommand::GetIndexes { collection });
}
for metric in ["stats", "dataSize", "storageSize", "totalIndexSize"] {
if let Some((args, tail)) = method_call(source, prefix_end, metric) {
if !tail.is_empty() || args.len() > 1 {
return Err(format!("Invalid MongoDB {metric}() command."));
}
let scale = args
.first()
.filter(|arg| !arg.trim().is_empty())
.map(|arg| {
arg.trim()
.parse::<f64>()
.ok()
.and_then(serde_json::Number::from_f64)
.ok_or_else(|| format!("Invalid {metric} scale."))
})
.transpose()?;
return Ok(MongoCommand::CollectionStats { collection, metric: metric.to_string(), scale });
}
}
if let Some((args, tail)) = method_call(source, prefix_end, "insertOne") {
if !tail.is_empty() || args.len() != 1 {
return Err("Invalid MongoDB insertOne() command.".to_string());
}
return Ok(MongoCommand::Insert { collection, documents: normalized_json(&args[0])? });
}
if let Some((args, tail)) = method_call(source, prefix_end, "insertMany") {
if !tail.is_empty() || args.len() != 1 {
return Err("Invalid MongoDB insertMany() command.".to_string());
}
let documents = normalized_json(&args[0])?;
if !parse_json_value(&documents).is_some_and(|value| value.is_array()) {
return Err("MongoDB insertMany() requires an array.".to_string());
}
return Ok(MongoCommand::Insert { collection, documents });
}
for (method, many) in [("updateOne", false), ("updateMany", true)] {
if let Some((args, tail)) = method_call(source, prefix_end, method) {
if !tail.is_empty() || !(2..=3).contains(&args.len()) {
return Err(format!("Invalid MongoDB {method}() command."));
}
return Ok(MongoCommand::Update {
collection,
filter: normalized_json(&args[0])?,
update: normalized_json(&args[1])?,
options: args
.get(2)
.filter(|arg| !arg.trim().is_empty())
.map(|arg| normalized_json(arg))
.transpose()?,
many,
});
}
}
for (method, many) in [("deleteOne", false), ("deleteMany", true)] {
if let Some((args, tail)) = method_call(source, prefix_end, method) {
if !tail.is_empty() || args.len() != 1 {
return Err(format!("Invalid MongoDB {method}() command."));
}
return Ok(MongoCommand::Delete { collection, filter: normalized_json(&args[0])?, many });
}
}
if let Some((args, tail)) = method_call(source, prefix_end, "createIndex") {
if !tail.is_empty() || !(1..=2).contains(&args.len()) {
return Err("Invalid MongoDB createIndex() command.".to_string());
}
return Ok(MongoCommand::CreateIndex {
collection,
keys: normalized_json(&args[0])?,
options: args.get(1).filter(|arg| !arg.trim().is_empty()).map(|arg| normalized_json(arg)).transpose()?,
});
}
if let Some((args, tail)) = method_call(source, prefix_end, "dropIndex") {
if !tail.is_empty() || args.len() != 1 {
return Err("Invalid MongoDB dropIndex() command.".to_string());
}
return Ok(MongoCommand::DropIndexes { collection, indexes: Some(normalized_json(&args[0])?), single: true });
}
if let Some((args, tail)) = method_call(source, prefix_end, "dropIndexes") {
if !tail.is_empty() || args.len() > 1 {
return Err("Invalid MongoDB dropIndexes() command.".to_string());
}
return Ok(MongoCommand::DropIndexes {
collection,
indexes: args.first().filter(|arg| !arg.trim().is_empty()).map(|arg| normalized_json(arg)).transpose()?,
single: false,
});
}
if let Some((args, tail)) = method_call(source, prefix_end, "drop") {
if !tail.is_empty() || !args.is_empty() {
return Err("Invalid MongoDB drop() command.".to_string());
}
return Ok(MongoCommand::DropCollection { collection });
}
Err("Unsupported MongoDB shell command.".to_string())
}
fn parse_collection_prefix(source: &str) -> Result<(String, usize), String> {
if !source.get(..3).is_some_and(|prefix| prefix.eq_ignore_ascii_case("db.")) {
return Err("MongoDB command must start with db.<collection>.".to_string());
}
let rest = &source[3..];
if rest.starts_with("getCollection") {
let open = rest.find('(').ok_or("Invalid db.getCollection() command.")?;
let close = matching_paren(rest, open).ok_or("Invalid db.getCollection() command.")?;
let args = split_top_level(&rest[open + 1..close]);
if args.len() != 1 {
return Err("db.getCollection() requires one collection name.".to_string());
}
let collection = parse_string_arg(&args[0])?;
let end = 3 + close + 1;
let suffix = &source[end..];
let trimmed = suffix.trim_start();
if !trimmed.starts_with('.') {
return Err("MongoDB collection method is required.".to_string());
}
return Ok((collection, end + suffix.len() - trimmed.len()));
}
let collection_end = rest
.char_indices()
.find_map(|(index, ch)| (ch == '.' || ch.is_whitespace()).then_some(index))
.ok_or("MongoDB collection method is required.")?;
let collection = &rest[..collection_end];
if collection.is_empty() {
return Err("Invalid MongoDB collection name.".to_string());
}
let suffix = &rest[collection_end..];
let dot = suffix.find('.').ok_or("MongoDB collection method is required.")?;
if !suffix[..dot].trim().is_empty() {
return Err("Invalid MongoDB collection name.".to_string());
}
Ok((collection.to_string(), 3 + collection_end + dot))
}
fn method_call(source: &str, prefix_end: usize, method: &str) -> Option<(Vec<String>, String)> {
let raw_suffix = &source[prefix_end..];
let suffix = raw_suffix.trim_start();
let whitespace = raw_suffix.len() - suffix.len();
let expected = format!(".{method}");
if !suffix.starts_with(&expected) || !suffix[expected.len()..].starts_with('(') {
return None;
}
let open = prefix_end + whitespace + expected.len();
let close = matching_paren(source, open)?;
Some((split_top_level(&source[open + 1..close]), source[close + 1..].trim().to_string()))
}
fn chained_calls(chain: &str) -> Result<Vec<(String, Vec<String>)>, String> {
let mut rest = chain.trim();
let mut calls = Vec::new();
while !rest.is_empty() {
let Some(rest_after_dot) = rest.strip_prefix('.') else {
return Err("Invalid MongoDB method chain.".to_string());
};
let open = rest_after_dot.find('(').ok_or("Invalid MongoDB method chain.")?;
let name = rest_after_dot[..open].trim().to_string();
let close = matching_paren(rest_after_dot, open).ok_or("Invalid MongoDB method chain.")?;
calls.push((name, split_top_level(&rest_after_dot[open + 1..close])));
rest = rest_after_dot[close + 1..].trim();
}
Ok(calls)
}
fn parse_integer(args: &[String], name: &str) -> Result<i64, String> {
if args.len() != 1 {
return Err(format!("MongoDB {name}() requires one integer."));
}
let value =
args[0].trim().parse::<i64>().map_err(|_| format!("MongoDB {name}() requires a non-negative integer."))?;
if value < 0 {
return Err(format!("MongoDB {name}() requires a non-negative integer."));
}
Ok(value)
}
fn parse_string_arg(arg: &str) -> Result<String, String> {
let value = parse_json_value(&normalized_json(arg)?).ok_or("Invalid MongoDB string argument.")?;
value.as_str().map(ToOwned::to_owned).ok_or_else(|| "MongoDB argument must be a string.".to_string())
}
fn normalized_json(input: &str) -> Result<String, String> {
let transformed = transform_shell_constructors(input.trim())?;
let value: Value =
json5::from_str(&transformed).map_err(|error| format!("Invalid MongoDB JSON argument: {error}"))?;
serde_json::to_string(&value).map_err(|error| error.to_string())
}
fn transform_shell_constructors(input: &str) -> Result<String, String> {
let mut output = String::with_capacity(input.len());
let mut index = 0;
while index < input.len() {
let rest = &input[index..];
let constructor = if rest.starts_with("ObjectId(") {
Some("ObjectId(")
} else if rest.starts_with("ISODate(") {
Some("ISODate(")
} else {
None
};
let Some(constructor) = constructor else {
let ch = rest.chars().next().ok_or("Invalid MongoDB argument.")?;
output.push(ch);
index += ch.len_utf8();
continue;
};
let open = index + constructor.len() - 1;
let close = matching_paren(input, open).ok_or("Unclosed MongoDB value constructor.")?;
let inner = input[open + 1..close].trim();
let value = parse_string_arg(inner)?;
let key = if constructor.starts_with("ObjectId") { "$oid" } else { "$date" };
output.push_str(&format!("{{\"{key}\":{}}}", serde_json::to_string(&value).unwrap()));
index = close + 1;
}
Ok(output)
}
fn parse_json_value(value: &str) -> Option<Value> {
serde_json::from_str(value).ok()
}
fn is_empty_object(value: &str) -> bool {
parse_json_value(value).is_some_and(|value| value.as_object().is_some_and(|object| object.is_empty()))
}
fn aggregate_writes(pipeline: &str) -> bool {
parse_json_value(pipeline).is_some_and(|value| {
value.as_array().is_some_and(|stages| {
stages.iter().any(|stage| {
stage
.as_object()
.is_some_and(|object| object.keys().any(|key| matches!(key.as_str(), "$out" | "$merge")))
})
})
})
}
fn matching_paren(source: &str, open: usize) -> Option<usize> {
let bytes = source.as_bytes();
let mut depth = 0;
let mut quote = None;
let mut escape = false;
for (index, byte) in bytes.iter().enumerate().skip(open) {
let ch = *byte as char;
if escape {
escape = false;
continue;
}
if quote.is_some() {
if ch == '\\' {
escape = true;
} else if Some(ch) == quote {
quote = None;
}
continue;
}
if ch == '\'' || ch == '"' || ch == '`' {
quote = Some(ch);
} else if ch == '(' {
depth += 1;
} else if ch == ')' {
depth -= 1;
if depth == 0 {
return Some(index);
}
}
}
None
}
fn split_top_level(source: &str) -> Vec<String> {
if source.trim().is_empty() {
return Vec::new();
}
let mut result = Vec::new();
let mut start = 0;
let mut depth = 0;
let mut quote = None;
let mut escape = false;
for (index, byte) in source.as_bytes().iter().enumerate() {
let ch = *byte as char;
if escape {
escape = false;
continue;
}
if quote.is_some() {
if ch == '\\' {
escape = true;
} else if Some(ch) == quote {
quote = None;
}
continue;
}
if ch == '\'' || ch == '"' || ch == '`' {
quote = Some(ch);
} else if matches!(ch, '(' | '[' | '{') {
depth += 1;
} else if matches!(ch, ')' | ']' | '}') {
depth -= 1;
} else if ch == ',' && depth == 0 {
result.push(source[start..index].trim().to_string());
start = index + 1;
}
}
result.push(source[start..].trim().to_string());
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_find_with_compass_syntax_and_chain() {
assert_eq!(
parse("db.products.find({_id: ObjectId('507f1f77bcf86cd799439011')}, {title: 1, _id: 0}).sort({title: 1}).limit(1)").unwrap(),
MongoCommand::Find {
collection: "products".to_string(),
filter: r#"{"_id":{"$oid":"507f1f77bcf86cd799439011"}}"#.to_string(),
projection: Some(r#"{"title":1,"_id":0}"#.to_string()),
sort: Some(r#"{"title":1}"#.to_string()),
skip: 0,
limit: 1,
}
);
}
#[test]
fn parses_get_collection_and_count() {
assert_eq!(
parse("db.getCollection('audit.logs').count()").unwrap(),
MongoCommand::Count { collection: "audit.logs".to_string(), filter: "{}".to_string(), accurate: false }
);
}
#[test]
fn identifies_dangerous_aggregate_and_empty_writes() {
let aggregate = parse(r#"db.projects.aggregate([{"$out":"backup"}])"#).unwrap();
assert!(aggregate.is_mutating());
assert!(aggregate.is_dangerous());
let update = parse("db.projects.updateMany({}, {$set: {active: false}})").unwrap();
assert!(update.has_empty_filter());
}
#[test]
fn accepts_multiline_chains_and_update_options() {
let command = parse(
r#"db.getCollection("operation_logs")
.find({_id: ObjectId("68ad51ca84c8127bc7d44cb3")})
.sort({ts: -1})
.skip(5)
.limit(10)"#,
)
.unwrap();
assert!(matches!(command, MongoCommand::Find { skip: 5, limit: 10, .. }));
let update = parse(
r#"db.orders.updateMany({status: "open"}, {$set: {"items.$[item].status": "done"}}, {arrayFilters: [{"item.id": 7}]})"#,
)
.unwrap();
assert!(matches!(update, MongoCommand::Update { many: true, options: Some(_), .. }));
}
#[test]
fn accepts_stats_and_rejects_negative_pagination() {
assert!(matches!(
parse("db.users.stats(1024)").unwrap(),
MongoCommand::CollectionStats { metric, scale: Some(_), .. } if metric == "stats"
));
assert!(parse("db.users.find({}).skip(-1)").is_err());
}
}
+26 -23
View File
@@ -9,8 +9,8 @@ use serde::Deserialize;
use serde_json::json;
use uuid::Uuid;
use crate::backend::{new_connection_config, parse_database_type, ConnectionSummary, DbxBackend};
use crate::mongo::{self, MongoCommand};
use crate::backend::{format_query_result, new_connection_config, parse_database_type, ConnectionSummary, DbxBackend};
use crate::mongo::{self, MongoCommand, MongoSafetyError};
use dbx_core::{
db::redis_driver::{classify_command, parse_command_argv, RedisCommandResult, RedisCommandSafety},
models::connection::DatabaseType,
@@ -262,7 +262,7 @@ impl DbxMcpServer {
Err(error) => return error,
};
return match self.backend.execute_mongo_command(&connection, &database, &command).await {
Ok(result) => text(result),
Ok(result) => text(format_query_result(&result, 100)),
Err(error) => tool_error("QUERY_ERROR", error),
};
}
@@ -644,26 +644,29 @@ fn validate_mongo_command(
)
})?;
let permissions = default_permissions();
if command.is_mutating() && !permissions.allow_writes {
return Err(tool_error(
"SQL_BLOCKED",
"MCP MongoDB execution is read-only for this session. Set DBX_MCP_ALLOW_WRITES=1 to allow write commands.",
));
}
if command.has_empty_filter() && !permissions.allow_dangerous {
return Err(tool_error(
"SQL_BLOCKED",
"MongoDB update/delete commands must include a non-empty filter unless DBX_MCP_ALLOW_DANGEROUS_SQL=1 is set.",
));
}
if command.is_dangerous() && !permissions.allow_dangerous {
return Err(tool_error(
"SQL_BLOCKED",
"Dangerous MongoDB command is blocked. Set DBX_MCP_ALLOW_DANGEROUS_SQL=1 to allow it.",
));
}
if command.is_mutating() && is_production_database(connection, database) {
return Err(tool_error("PRODUCTION_WRITE_BLOCKED", "MCP cannot execute writes against a production database."));
if let Err(error) = mongo::validate_safety(
&command,
permissions.allow_writes,
permissions.allow_dangerous,
is_production_database(connection, database),
) {
return Err(match error {
MongoSafetyError::WritesDisabled => tool_error(
"SQL_BLOCKED",
"MCP MongoDB execution is read-only for this session. Set DBX_MCP_ALLOW_WRITES=1 to allow write commands.",
),
MongoSafetyError::EmptyFilter => tool_error(
"SQL_BLOCKED",
"MongoDB update/delete commands must include a non-empty filter unless DBX_MCP_ALLOW_DANGEROUS_SQL=1 is set.",
),
MongoSafetyError::Dangerous => tool_error(
"SQL_BLOCKED",
"Dangerous MongoDB command is blocked. Set DBX_MCP_ALLOW_DANGEROUS_SQL=1 to allow it.",
),
MongoSafetyError::ProductionWrite => {
tool_error("PRODUCTION_WRITE_BLOCKED", "MCP cannot execute writes against a production database.")
}
});
}
Ok(command)
}
+1 -1
View File
@@ -78,7 +78,7 @@ async fn executes_mongo_shell_commands_without_desktop_process() {
std::env::set_var("DBX_MCP_ALLOW_WRITES", "1");
call_query(&client, "db.items.deleteOne({_id: 'rust-mcp-e2e'})").await;
call_query(&client, "db.items.insertOne({_id: 'rust-mcp-e2e', name: 'Ada'})").await;
call_query(&client, "db.items.insert({_id: 'rust-mcp-e2e', name: 'Ada'})").await;
let result = call_query(&client, "db.items.find({_id: 'rust-mcp-e2e'}).limit(1)").await;
assert!(result.contains("Ada"), "unexpected MongoDB result: {result}");
call_query(&client, "db.items.deleteOne({_id: 'rust-mcp-e2e'})").await;