package dbs import ( "encoding/json" "fmt" "strings" "time" "git.x2erp.com/qdy/go-svc-mcp/internal/mcp" ) func init() { mcp.Register("get_mysql_tables", "获取MySQL数据库中的所有表和描述", map[string]interface{}{ "type": "object", "properties": map[string]interface{}{ "include_system_tables": map[string]interface{}{ "type": "boolean", "description": "是否包含系统表", "default": false, }, "schema": map[string]interface{}{ "type": "string", "description": "数据库名称(默认为当前数据库)", "default": "", }, "database_key": map[string]interface{}{ "type": "string", "description": "数据库配置键名(如:business),可选,默认使用主数据库", "enum": []string{"warehouse", "business"}, "default": "", }, }, "required": []string{}, }, func(input json.RawMessage, deps *mcp.ToolDependencies) (interface{}, error) { var params struct { IncludeSystemTables bool `json:"include_system_tables"` Schema string `json:"schema"` DatabaseKey string `json:"database_key"` } if len(input) > 0 { if err := json.Unmarshal(input, ¶ms); err != nil { return nil, err } } // 获取数据库工厂 dbFactory, err := GetDBFactory(params.DatabaseKey, deps) if err != nil { return nil, err } // 获取数据库类型,确保是MySQL dbType := dbFactory.GetDBType() if dbType != "mysql" { return nil, fmt.Errorf("数据库类型为 %s,此工具仅支持MySQL数据库", dbType) } // 获取当前数据库名称 currentDatabase := dbFactory.GetDatabaseName() schema := strings.TrimSpace(params.Schema) if schema == "" { schema = currentDatabase } // 构建查询SQL var query string if params.IncludeSystemTables { query = ` SELECT TABLE_NAME as table_name, TABLE_COMMENT as table_description FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_TYPE = 'BASE TABLE' ORDER BY TABLE_NAME` } else { query = ` SELECT TABLE_NAME as table_name, TABLE_COMMENT as table_description FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME NOT LIKE 'mysql%' AND TABLE_NAME NOT LIKE 'sys%' AND TABLE_NAME NOT LIKE 'performance_schema%' AND TABLE_NAME NOT LIKE 'information_schema%' ORDER BY TABLE_NAME` } // 执行查询 results, err := dbFactory.QuerySliceMapWithParams(query, schema) if err != nil { return nil, fmt.Errorf("查询表信息失败: %v", err) } // 如果没有描述信息,设置为空字符串 for i := range results { if results[i]["table_description"] == nil { results[i]["table_description"] = "" } } return map[string]interface{}{ "tenant_id": deps.ReqCtx.TenantID, "user_id": deps.ReqCtx.UserID, "database_type": dbType, "database_name": dbFactory.GetDatabaseName(), "schema": schema, "include_system_tables": params.IncludeSystemTables, "tables": results, "total_tables": len(results), "timestamp": time.Now().Format(time.RFC3339), }, nil }, ) }