3 files changed
+213
-25
No files matched your search
@@ -5,7 +5,7 @@ use crate::db::mongo_driver::{
|
|||||||
};
|
};
|
||||||
use crate::document_ops::CollectionInfo;
|
use crate::document_ops::CollectionInfo;
|
||||||
use crate::mongo_shell::MongoCommand;
|
use crate::mongo_shell::MongoCommand;
|
||||||
use crate::types::QueryResult;
|
use crate::types::{IndexInfo, QueryResult};
|
||||||
|
|
||||||
async fn ensure_document_pool(state: &AppState, connection_id: &str) -> Result<(), String> {
|
async fn ensure_document_pool(state: &AppState, connection_id: &str) -> Result<(), String> {
|
||||||
state.get_or_create_pool(connection_id, None).await.map(|_| ())
|
state.get_or_create_pool(connection_id, None).await.map(|_| ())
|
||||||
@@ -751,17 +751,8 @@ pub async fn execute_mongo_command_core(
|
|||||||
Ok(mongo_documents_query_result(limit_mongo_documents(result, max_rows).documents))
|
Ok(mongo_documents_query_result(limit_mongo_documents(result, max_rows).documents))
|
||||||
}
|
}
|
||||||
MongoCommand::GetIndexes { collection } => {
|
MongoCommand::GetIndexes { collection } => {
|
||||||
let result = mongo_aggregate_documents_core(
|
let indexes = crate::schema::list_indexes_core(state, connection_id, database, "", collection).await?;
|
||||||
state,
|
Ok(mongo_indexes_query_result(indexes, max_rows))
|
||||||
connection_id,
|
|
||||||
database,
|
|
||||||
collection,
|
|
||||||
r#"[{"$indexStats":{}}]"#,
|
|
||||||
Some(max_rows),
|
|
||||||
None,
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
Ok(mongo_documents_query_result(result.documents))
|
|
||||||
}
|
}
|
||||||
MongoCommand::CollectionStats { collection, metric, scale } => {
|
MongoCommand::CollectionStats { collection, metric, scale } => {
|
||||||
let stats = mongo_collection_stats_core(state, connection_id, database, collection, scale.clone()).await?;
|
let stats = mongo_collection_stats_core(state, connection_id, database, collection, scale.clone()).await?;
|
||||||
@@ -901,6 +892,38 @@ fn affected_query_result(affected_rows: u64) -> QueryResult {
|
|||||||
query_result(Vec::new(), Vec::new(), affected_rows)
|
query_result(Vec::new(), Vec::new(), affected_rows)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn mongo_indexes_query_result(indexes: Vec<IndexInfo>, max_rows: usize) -> QueryResult {
|
||||||
|
use serde_json::Value;
|
||||||
|
|
||||||
|
let rows = indexes
|
||||||
|
.into_iter()
|
||||||
|
.take(max_rows.max(1))
|
||||||
|
.map(|index| {
|
||||||
|
vec![
|
||||||
|
Value::String(index.name),
|
||||||
|
Value::String(index.columns.join(", ")),
|
||||||
|
Value::Bool(index.is_unique),
|
||||||
|
Value::Bool(index.is_primary),
|
||||||
|
index.index_type.map(Value::String).unwrap_or(Value::Null),
|
||||||
|
index.filter.map(Value::String).unwrap_or(Value::Null),
|
||||||
|
]
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
let affected_rows = rows.len() as u64;
|
||||||
|
query_result(
|
||||||
|
vec![
|
||||||
|
"name".to_string(),
|
||||||
|
"columns".to_string(),
|
||||||
|
"unique".to_string(),
|
||||||
|
"primary".to_string(),
|
||||||
|
"type".to_string(),
|
||||||
|
"filter".to_string(),
|
||||||
|
],
|
||||||
|
rows,
|
||||||
|
affected_rows,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
fn mongo_drop_indexes_query_result(
|
fn mongo_drop_indexes_query_result(
|
||||||
dropped_names: Vec<String>,
|
dropped_names: Vec<String>,
|
||||||
failures: Vec<(String, String)>,
|
failures: Vec<(String, String)>,
|
||||||
@@ -1239,6 +1262,49 @@ for line in sys.stdin:
|
|||||||
assert_eq!(name, "email_1");
|
assert_eq!(name, "email_1");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn mongo_indexes_query_result_matches_desktop_contract_and_limits_rows() {
|
||||||
|
let result = mongo_indexes_query_result(
|
||||||
|
vec![
|
||||||
|
IndexInfo {
|
||||||
|
name: "_id_".to_string(),
|
||||||
|
columns: vec!["_id".to_string()],
|
||||||
|
is_unique: false,
|
||||||
|
is_primary: true,
|
||||||
|
filter: None,
|
||||||
|
index_type: Some("_id: 1".to_string()),
|
||||||
|
included_columns: None,
|
||||||
|
comment: None,
|
||||||
|
},
|
||||||
|
IndexInfo {
|
||||||
|
name: "email_1".to_string(),
|
||||||
|
columns: vec!["email".to_string()],
|
||||||
|
is_unique: true,
|
||||||
|
is_primary: false,
|
||||||
|
filter: Some("{\"active\":true}".to_string()),
|
||||||
|
index_type: Some("email: 1".to_string()),
|
||||||
|
included_columns: None,
|
||||||
|
comment: None,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
1,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(result.columns, ["name", "columns", "unique", "primary", "type", "filter"]);
|
||||||
|
assert_eq!(
|
||||||
|
result.rows,
|
||||||
|
[vec![
|
||||||
|
serde_json::json!("_id_"),
|
||||||
|
serde_json::json!("_id"),
|
||||||
|
serde_json::json!(false),
|
||||||
|
serde_json::json!(true),
|
||||||
|
serde_json::json!("_id: 1"),
|
||||||
|
serde_json::Value::Null,
|
||||||
|
]]
|
||||||
|
);
|
||||||
|
assert_eq!(result.affected_rows, 1);
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn mongo_create_index_requires_a_name_from_the_legacy_agent() {
|
async fn mongo_create_index_requires_a_name_from_the_legacy_agent() {
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ use dbx_core::{
|
|||||||
agent_events::{ToolCall, ToolResult},
|
agent_events::{ToolCall, ToolResult},
|
||||||
agent_tools::{self, AgentSqlPermissions},
|
agent_tools::{self, AgentSqlPermissions},
|
||||||
connection::AppState,
|
connection::AppState,
|
||||||
db::{redis_driver::RedisCommandResult, ColumnInfo, TableInfo},
|
db::{redis_driver::RedisCommandResult, ColumnInfo, IndexInfo, TableInfo},
|
||||||
models::connection::{ConnectionConfig, DatabaseType},
|
models::connection::{ConnectionConfig, DatabaseType},
|
||||||
storage::{DesktopSettings, McpGlobalPolicy, McpGlobalPolicyState, Storage},
|
storage::{DesktopSettings, McpGlobalPolicy, McpGlobalPolicyState, Storage},
|
||||||
};
|
};
|
||||||
@@ -960,23 +960,22 @@ impl DbxBackend for WebBackend {
|
|||||||
Ok(mongo_documents_query_result(result.documents))
|
Ok(mongo_documents_query_result(result.documents))
|
||||||
}
|
}
|
||||||
MongoCommand::GetIndexes { collection } => {
|
MongoCommand::GetIndexes { collection } => {
|
||||||
let result = self
|
let indexes = self
|
||||||
.request(
|
.request(
|
||||||
reqwest::Method::POST,
|
reqwest::Method::GET,
|
||||||
"/api/mongo/aggregate-documents",
|
&format!(
|
||||||
Some(json!({
|
"/api/schema/indexes?connection_id={}&database={}&schema=&table={}",
|
||||||
"connectionId": connection_id,
|
url_encode(connection_id),
|
||||||
"database": database,
|
url_encode(database),
|
||||||
"collection": collection,
|
url_encode(collection)
|
||||||
"pipelineJson": r#"[{"$indexStats":{}}]"#,
|
),
|
||||||
"maxRows": 100,
|
None,
|
||||||
})),
|
|
||||||
)
|
)
|
||||||
.await?
|
.await?
|
||||||
.json::<WebMongoDocuments>()
|
.json::<Vec<IndexInfo>>()
|
||||||
.await
|
.await
|
||||||
.map_err(|error| format!("Invalid MongoDB indexes response: {error}"))?;
|
.map_err(|error| format!("Invalid MongoDB indexes response: {error}"))?;
|
||||||
Ok(mongo_documents_query_result(result.documents))
|
Ok(dbx_core::mongo_ops::mongo_indexes_query_result(indexes, 100))
|
||||||
}
|
}
|
||||||
MongoCommand::CollectionStats { collection, metric, scale } => {
|
MongoCommand::CollectionStats { collection, metric, scale } => {
|
||||||
let value: Value = self
|
let value: Value = self
|
||||||
@@ -1431,6 +1430,12 @@ pub fn new_connection_config(
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use std::{
|
||||||
|
io::{Read, Write},
|
||||||
|
net::TcpListener,
|
||||||
|
sync::mpsc,
|
||||||
|
time::Duration,
|
||||||
|
};
|
||||||
|
|
||||||
fn policy_state(configured: bool, read_only: bool) -> McpGlobalPolicyState {
|
fn policy_state(configured: bool, read_only: bool) -> McpGlobalPolicyState {
|
||||||
McpGlobalPolicyState { configured, read_only, allow_dangerous_sql: false, allowed_connection_ids: None }
|
McpGlobalPolicyState { configured, read_only, allow_dangerous_sql: false, allowed_connection_ids: None }
|
||||||
@@ -1509,6 +1514,82 @@ mod tests {
|
|||||||
assert_eq!(result.affected_rows, 1);
|
assert_eq!(result.affected_rows, 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn web_mongo_get_indexes_uses_schema_indexes_endpoint() {
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||||
|
let address = listener.local_addr().unwrap();
|
||||||
|
let (request_sender, request_receiver) = mpsc::channel();
|
||||||
|
let server = std::thread::spawn(move || {
|
||||||
|
let (mut stream, _) = listener.accept().unwrap();
|
||||||
|
stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||||
|
let mut request = Vec::new();
|
||||||
|
let mut buffer = [0_u8; 1024];
|
||||||
|
loop {
|
||||||
|
let count = stream.read(&mut buffer).unwrap();
|
||||||
|
request.extend_from_slice(&buffer[..count]);
|
||||||
|
if count == 0 || request.windows(4).any(|window| window == b"\r\n\r\n") {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let request = String::from_utf8(request).unwrap();
|
||||||
|
let request_line = request.lines().next().unwrap().to_string();
|
||||||
|
request_sender.send(request_line.clone()).unwrap();
|
||||||
|
let body = if request_line.starts_with("GET /api/schema/indexes?") {
|
||||||
|
r#"[{"name":"email_1","columns":["email"],"is_unique":true,"is_primary":false,"filter":null,"index_type":"email: 1","included_columns":null,"comment":null}]"#
|
||||||
|
} else {
|
||||||
|
r#"{"documents":[{"name":"email_1","columns":["email"],"is_unique":true,"is_primary":false,"filter":null,"index_type":"email: 1"}]}"#
|
||||||
|
};
|
||||||
|
write!(
|
||||||
|
stream,
|
||||||
|
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
|
||||||
|
body.len(),
|
||||||
|
body
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
});
|
||||||
|
|
||||||
|
let backend = WebBackend::new(format!("http://{address}"), String::new()).unwrap();
|
||||||
|
backend.auth.lock().await.checked = true;
|
||||||
|
let connection = new_connection_config(
|
||||||
|
"legacy".to_string(),
|
||||||
|
"Legacy MongoDB".to_string(),
|
||||||
|
DatabaseType::MongoDb,
|
||||||
|
"localhost".to_string(),
|
||||||
|
27017,
|
||||||
|
String::new(),
|
||||||
|
String::new(),
|
||||||
|
Some("app".to_string()),
|
||||||
|
false,
|
||||||
|
Some("mongodb-legacy".to_string()),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
backend.connected.lock().await.insert(connection.id.clone(), connection.clone());
|
||||||
|
|
||||||
|
let result = backend
|
||||||
|
.execute_mongo_command(&connection, "app", &MongoCommand::GetIndexes { collection: "im_msg".to_string() })
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
server.join().unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
request_receiver.recv().unwrap(),
|
||||||
|
"GET /api/schema/indexes?connection_id=legacy&database=app&schema=&table=im_msg HTTP/1.1"
|
||||||
|
);
|
||||||
|
assert_eq!(result.columns, ["name", "columns", "unique", "primary", "type", "filter"]);
|
||||||
|
assert_eq!(
|
||||||
|
result.rows,
|
||||||
|
[vec![
|
||||||
|
Value::String("email_1".to_string()),
|
||||||
|
Value::String("email".to_string()),
|
||||||
|
Value::Bool(true),
|
||||||
|
Value::Bool(false),
|
||||||
|
Value::String("email: 1".to_string()),
|
||||||
|
Value::Null,
|
||||||
|
]]
|
||||||
|
);
|
||||||
|
assert_eq!(result.affected_rows, 1);
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn local_backend_uses_desktop_plugin_directory() {
|
async fn local_backend_uses_desktop_plugin_directory() {
|
||||||
let data_dir = tempfile::tempdir().unwrap();
|
let data_dir = tempfile::tempdir().unwrap();
|
||||||
|
|||||||
@@ -259,6 +259,47 @@ async fn executes_mongo_shell_commands_without_desktop_process() {
|
|||||||
server_task.abort();
|
server_task.abort();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
#[ignore = "requires DBX_MCP_TEST_MONGO_HOST and DBX_MCP_TEST_MONGO_PORT pointing at MongoDB 4.0+"]
|
||||||
|
async fn executes_legacy_mongo_get_indexes_without_desktop_process() {
|
||||||
|
let host = std::env::var("DBX_MCP_TEST_MONGO_HOST").expect("MongoDB host");
|
||||||
|
let port = std::env::var("DBX_MCP_TEST_MONGO_PORT")
|
||||||
|
.unwrap_or_else(|_| "27017".to_string())
|
||||||
|
.parse::<u16>()
|
||||||
|
.expect("MongoDB port");
|
||||||
|
let directory = tempdir().expect("temporary data directory");
|
||||||
|
let db_path = directory.path().join("dbx.db");
|
||||||
|
let storage = Storage::open(&db_path).await.expect("open storage");
|
||||||
|
let connection: ConnectionConfig = serde_json::from_value(json!({
|
||||||
|
"id": "mongo-e2e",
|
||||||
|
"name": "mongo-legacy-e2e",
|
||||||
|
"db_type": "mongodb",
|
||||||
|
"driver_profile": "mongodb-legacy",
|
||||||
|
"host": host,
|
||||||
|
"port": port,
|
||||||
|
"username": "",
|
||||||
|
"password": "",
|
||||||
|
"database": "dbx_mcp_test",
|
||||||
|
"ssl": false
|
||||||
|
}))
|
||||||
|
.expect("MongoDB Legacy connection config");
|
||||||
|
storage.save_connections(&[connection]).await.expect("save connection");
|
||||||
|
|
||||||
|
let backend = Arc::new(LocalBackend::open(&db_path).await.expect("open local backend"));
|
||||||
|
let server = DbxMcpServer::with_runtime_options(backend, McpScope::default(), false);
|
||||||
|
let (server_transport, client_transport) = tokio::io::duplex(32 * 1024);
|
||||||
|
let server_task = tokio::spawn(async move { server.serve(server_transport).await });
|
||||||
|
let client = ().serve(client_transport).await.expect("initialize client");
|
||||||
|
|
||||||
|
let result = call_query(&client, "db.im_msg.getIndexes()").await;
|
||||||
|
assert!(result.contains("| name | columns | unique | primary | type | filter |"), "{result}");
|
||||||
|
assert!(result.contains("_id_"), "{result}");
|
||||||
|
assert!(result.contains("email_1"), "{result}");
|
||||||
|
|
||||||
|
client.cancel().await.expect("close client");
|
||||||
|
server_task.abort();
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg(feature = "mq-admin")]
|
#[cfg(feature = "mq-admin")]
|
||||||
fn mcp_default_features_include_message_queue_admin() {
|
fn mcp_default_features_include_message_queue_admin() {
|
||||||
|
|||||||
Reference in new issue
Block a user