25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
fix(mongodb): include TTL index info in MCP getIndexes
jearhe38b93505c4b0
diff --git a/crates/dbx-core/src/mongo_ops.rs b/crates/dbx-core/src/mongo_ops.rsindex 606dab4afe..e60d75d3b8 100644--- a/crates/dbx-core/src/mongo_ops.rs+++ b/crates/dbx-core/src/mongo_ops.rs@@ -6,7 +6,7 @@ use crate::db::mongo_driver::{};use crate::document_ops::CollectionInfo;use crate::mongo_shell::MongoCommand;-use crate::types::{IndexInfo, QueryResult};+use crate::types::QueryResult;pub const MONGO_SHOW_DATABASES_DATABASE: &str = "admin";pub const MONGO_SHOW_DATABASES_COMMAND_JSON: &str = r#"{"listDatabases":1}"#;@@ -1009,8 +1009,8 @@ pub async fn execute_mongo_command_core(Ok(mongo_documents_query_result(limit_mongo_documents(result, max_rows).documents))}MongoCommand::GetIndexes { collection } => {- let indexes = crate::schema::list_indexes_core(state, connection_id, database, "", collection).await?;- Ok(mongo_indexes_query_result(indexes, max_rows))+ let specs = mongo_list_index_specs_core(state, connection_id, database, collection).await?;+ Ok(mongo_indexes_query_result(specs, max_rows))}MongoCommand::CollectionStats { collection, metric, scale } => {let stats = mongo_collection_stats_core(state, connection_id, database, collection, scale.clone()).await?;@@ -1156,20 +1156,38 @@ fn affected_query_result(affected_rows: u64) -> QueryResult {query_result(Vec::new(), Vec::new(), affected_rows)}-pub fn mongo_indexes_query_result(indexes: Vec<IndexInfo>, max_rows: usize) -> QueryResult {+/// Format [`MongoIndexSpec`]s the way the desktop index panel reports them, plus+/// the TTL column (`expireAfterSeconds`) that the shared `IndexInfo` could never carry.+pub fn mongo_indexes_query_result(indexes: Vec<mongo_driver::MongoIndexSpec>, max_rows: usize) -> QueryResult {use serde_json::Value;let rows = indexes.into_iter().take(max_rows.max(1)).map(|index| {+ let columns = index.keys.iter().map(|key| key.field.clone()).collect::<Vec<_>>().join(", ");+ let index_type = index.keys.iter().any(|key| !key.direction.is_empty()).then(|| {+ index+ .keys+ .iter()+ .map(|key| {+ if key.direction.is_empty() {+ key.field.clone()+ } else {+ format!("{}: {}", key.field, key.direction)+ }+ })+ .collect::<Vec<_>>()+ .join(", ")+ });vec![Value::String(index.name),- Value::String(index.columns.join(", ")),+ Value::String(columns),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),+ index_type.map(Value::String).unwrap_or(Value::Null),+ index.partial_filter_expression.map(Value::String).unwrap_or(Value::Null),+ index.expire_after_seconds.map(Value::from).unwrap_or(Value::Null),]}).collect::<Vec<_>>();@@ -1182,6 +1200,7 @@ pub fn mongo_indexes_query_result(indexes: Vec<IndexInfo>, max_rows: usize) -> Q"primary".to_string(),"type".to_string(),"filter".to_string(),+ "expireAfterSeconds".to_string(),],rows,affected_rows,@@ -1843,47 +1862,123 @@ for line in sys.stdin:fn mongo_indexes_query_result_matches_desktop_contract_and_limits_rows() {let result = mongo_indexes_query_result(vec![- IndexInfo {+ mongo_driver::MongoIndexSpec {name: "_id_".to_string(),- columns: vec!["_id".to_string()],- is_unique: false,+ keys: vec![mongo_driver::MongoIndexKey { field: "_id".to_string(), direction: "1".to_string() }],+ is_unique: true,is_primary: true,- filter: None,- index_type: Some("_id: 1".to_string()),- included_columns: None,- comment: None,- key_is_expression: Vec::new(),+ is_sparse: false,+ expire_after_seconds: None,+ partial_filter_expression: None,+ background: false,+ bucket_size: None,+ hidden: false,+ properties_complete: true,+ extra_options: None,},- IndexInfo {+ mongo_driver::MongoIndexSpec {name: "email_1".to_string(),- columns: vec!["email".to_string()],+ keys: vec![mongo_driver::MongoIndexKey { field: "email".to_string(), direction: "1".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,- key_is_expression: Vec::new(),+ is_sparse: false,+ expire_after_seconds: None,+ partial_filter_expression: Some("{\"active\":true}".to_string()),+ background: false,+ bucket_size: None,+ hidden: false,+ properties_complete: true,+ extra_options: None,},],1,);- assert_eq!(result.columns, ["name", "columns", "unique", "primary", "type", "filter"]);+ assert_eq!(result.columns, ["name", "columns", "unique", "primary", "type", "filter", "expireAfterSeconds"]);assert_eq!(result.rows,[vec![serde_json::json!("_id_"),serde_json::json!("_id"),- serde_json::json!(false),+ serde_json::json!(true),serde_json::json!(true),serde_json::json!("_id: 1"),serde_json::Value::Null,+ serde_json::Value::Null,]]);assert_eq!(result.affected_rows, 1);}+ #[test]+ fn mongo_indexes_query_result_preserves_ttl_expiry_and_compound_keys() {+ let result = mongo_indexes_query_result(+ vec![+ mongo_driver::MongoIndexSpec {+ name: "createdAt_1".to_string(),+ keys: vec![mongo_driver::MongoIndexKey {+ field: "createdAt".to_string(),+ direction: "1".to_string(),+ }],+ is_unique: false,+ is_primary: false,+ is_sparse: false,+ expire_after_seconds: Some(3600),+ partial_filter_expression: None,+ background: false,+ bucket_size: None,+ hidden: false,+ properties_complete: true,+ extra_options: None,+ },+ mongo_driver::MongoIndexSpec {+ name: "tenantId_1_createdAt_-1".to_string(),+ keys: vec![+ mongo_driver::MongoIndexKey { field: "tenantId".to_string(), direction: "1".to_string() },+ mongo_driver::MongoIndexKey { field: "createdAt".to_string(), direction: "-1".to_string() },+ ],+ is_unique: false,+ is_primary: false,+ is_sparse: false,+ expire_after_seconds: None,+ partial_filter_expression: Some("{\"status\":\"active\"}".to_string()),+ background: false,+ bucket_size: None,+ hidden: false,+ properties_complete: true,+ extra_options: None,+ },+ ],+ 100,+ );++ assert_eq!(result.columns, ["name", "columns", "unique", "primary", "type", "filter", "expireAfterSeconds"]);+ assert_eq!(+ result.rows,+ [+ vec![+ serde_json::json!("createdAt_1"),+ serde_json::json!("createdAt"),+ serde_json::json!(false),+ serde_json::json!(false),+ serde_json::json!("createdAt: 1"),+ serde_json::Value::Null,+ serde_json::json!(3600),+ ],+ vec![+ serde_json::json!("tenantId_1_createdAt_-1"),+ serde_json::json!("tenantId, createdAt"),+ serde_json::json!(false),+ serde_json::json!(false),+ serde_json::json!("tenantId: 1, createdAt: -1"),+ serde_json::json!("{\"status\":\"active\"}"),+ serde_json::Value::Null,+ ],+ ]+ );+ assert_eq!(result.affected_rows, 2);+ }+#[cfg(unix)]#[tokio::test]async fn mongo_create_index_requires_a_name_from_the_legacy_agent() {diff --git a/crates/dbx-mcp/src/backend.rs b/crates/dbx-mcp/src/backend.rsindex da1b4a49fd..8520733b0b 100644--- a/crates/dbx-mcp/src/backend.rs+++ b/crates/dbx-mcp/src/backend.rs@@ -9,7 +9,7 @@ use dbx_core::{agent_events::{ToolCall, ToolResult},agent_tools::{self, format_query_result_as_text, AgentSqlPermissions, QueryCellWindow},connection::AppState,- db::{redis_driver::RedisCommandResult, ColumnInfo, IndexInfo, TableInfo},+ db::{mongo_driver::MongoIndexSpec, redis_driver::RedisCommandResult, ColumnInfo, TableInfo},models::connection::{ConnectionConfig, DatabaseType},storage::{DesktopSettings, McpGlobalPolicy, McpGlobalPolicyState, Storage},};@@ -1344,22 +1344,21 @@ impl DbxBackend for WebBackend {Ok(mongo_documents_query_result(result.documents))}MongoCommand::GetIndexes { collection } => {- let indexes = self+ let specs = self.request(- reqwest::Method::GET,- &format!(- "/api/schema/indexes?connection_id={}&database={}&schema=&table={}",- url_encode(connection_id),- url_encode(database),- url_encode(collection)- ),- None,+ reqwest::Method::POST,+ "/api/mongo/list-index-specs",+ Some(json!({+ "connectionId": connection_id,+ "database": database,+ "collection": collection,+ })),).await?- .json::<Vec<IndexInfo>>()+ .json::<Vec<MongoIndexSpec>>().await- .map_err(|error| format!("Invalid MongoDB indexes response: {error}"))?;- Ok(dbx_core::mongo_ops::mongo_indexes_query_result(indexes, 100))+ .map_err(|error| format!("Invalid MongoDB index specs response: {error}"))?;+ Ok(dbx_core::mongo_ops::mongo_indexes_query_result(specs, 100))}MongoCommand::CollectionStats { collection, metric, scale } => {let value: Value = self@@ -2244,7 +2243,7 @@ mod tests {}#[tokio::test]- async fn web_mongo_get_indexes_uses_schema_indexes_endpoint() {+ async fn web_mongo_get_indexes_uses_list_index_specs_endpoint() {let listener = TcpListener::bind("127.0.0.1:0").unwrap();let address = listener.local_addr().unwrap();let (request_sender, request_receiver) = mpsc::channel();@@ -2253,21 +2252,63 @@ mod tests {stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap();let mut request = Vec::new();let mut buffer = [0_u8; 1024];- loop {+ let header_end = 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") {+ if let Some(position) = request.windows(4).position(|window| window == b"\r\n\r\n") {+ break position + 4;+ }+ };+ let request_text = String::from_utf8_lossy(&request);+ let request_line = request_text.lines().next().unwrap().to_string();+ let content_length = request_text+ .lines()+ .find_map(|line| {+ let (name, value) = line.split_once(':')?;+ name.eq_ignore_ascii_case("content-length").then_some(value.trim())+ })+ .unwrap()+ .parse::<usize>()+ .unwrap();+ while request.len() < header_end + content_length {+ let count = stream.read(&mut buffer).unwrap();+ if count == 0 {break;}+ request.extend_from_slice(&buffer[..count]);}- 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"}]}"#- };+ let request_body = String::from_utf8_lossy(&request[header_end..]).to_string();+ request_sender.send((request_line.clone(), request_body)).unwrap();+ let body = r#"[+ {+ "name": "_id_",+ "keys": [{"field": "_id", "direction": "1"}],+ "is_unique": true,+ "is_primary": true,+ "is_sparse": false,+ "expire_after_seconds": null,+ "partial_filter_expression": null,+ "background": false,+ "bucket_size": null,+ "hidden": false,+ "properties_complete": true,+ "extra_options": null+ },+ {+ "name": "createdAt_1",+ "keys": [{"field": "createdAt", "direction": "1"}],+ "is_unique": false,+ "is_primary": false,+ "is_sparse": false,+ "expire_after_seconds": 3600,+ "partial_filter_expression": null,+ "background": false,+ "bucket_size": null,+ "hidden": false,+ "properties_complete": true,+ "extra_options": null+ }+ ]"#;write!(stream,"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",@@ -2300,23 +2341,35 @@ mod tests {.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"]);+ let (request_line, request_body) = request_receiver.recv().unwrap();+ assert_eq!(request_line, "POST /api/mongo/list-index-specs HTTP/1.1");+ let request_json: Value = serde_json::from_str(&request_body).unwrap();+ assert_eq!(request_json, json!({"connectionId": "legacy", "database": "app", "collection": "im_msg"}));+ assert_eq!(result.columns, ["name", "columns", "unique", "primary", "type", "filter", "expireAfterSeconds"]);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,- ]]+ [+ vec![+ Value::String("_id_".to_string()),+ Value::String("_id".to_string()),+ Value::Bool(true),+ Value::Bool(true),+ Value::String("_id: 1".to_string()),+ Value::Null,+ Value::Null,+ ],+ vec![+ Value::String("createdAt_1".to_string()),+ Value::String("createdAt".to_string()),+ Value::Bool(false),+ Value::Bool(false),+ Value::String("createdAt: 1".to_string()),+ Value::Null,+ Value::from(3600),+ ],+ ]);- assert_eq!(result.affected_rows, 1);+ assert_eq!(result.affected_rows, 2);}#[tokio::test]