fix(mcp): route MongoDB getIndexes through metadata

Closes #5618
This commit is contained in:
t8y2 committed 2026-08-07 17:21:31 +08:00
1 parent 43234ed47d
commit bac8f4166f
3 files changed
+213 -25

No files matched your search

+94 -13
View File
@@ -9,7 +9,7 @@ use dbx_core::{
agent_events::{ToolCall, ToolResult},
agent_tools::{self, AgentSqlPermissions},
connection::AppState,
db::{redis_driver::RedisCommandResult, ColumnInfo, TableInfo},
db::{redis_driver::RedisCommandResult, ColumnInfo, IndexInfo, TableInfo},
models::connection::{ConnectionConfig, DatabaseType},
storage::{DesktopSettings, McpGlobalPolicy, McpGlobalPolicyState, Storage},
};
@@ -960,23 +960,22 @@ impl DbxBackend for WebBackend {
Ok(mongo_documents_query_result(result.documents))
}
MongoCommand::GetIndexes { collection } => {
let result = self
let indexes = self
.request(
reqwest::Method::POST,
"/api/mongo/aggregate-documents",
Some(json!({
"connectionId": connection_id,
"database": database,
"collection": collection,
"pipelineJson": r#"[{"$indexStats":{}}]"#,
"maxRows": 100,
})),
reqwest::Method::GET,
&format!(
"/api/schema/indexes?connection_id={}&database={}&schema=&table={}",
url_encode(connection_id),
url_encode(database),
url_encode(collection)
),
None,
)
.await?
.json::<WebMongoDocuments>()
.json::<Vec<IndexInfo>>()
.await
.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 } => {
let value: Value = self
@@ -1431,6 +1430,12 @@ pub fn new_connection_config(
#[cfg(test)]
mod tests {
use super::*;
use std::{
io::{Read, Write},
net::TcpListener,
sync::mpsc,
time::Duration,
};
fn policy_state(configured: bool, read_only: bool) -> McpGlobalPolicyState {
McpGlobalPolicyState { configured, read_only, allow_dangerous_sql: false, allowed_connection_ids: None }
@@ -1509,6 +1514,82 @@ mod tests {
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]
async fn local_backend_uses_desktop_plugin_directory() {
let data_dir = tempfile::tempdir().unwrap();