package dbs import ( "encoding/json" "fmt" "strings" "time" "git.x2erp.com/qdy/go-svc-mcp/internal/mcp" ) func init() { mcp.Register("get_sqlserver_tables", "获取SQL Server数据库中的所有表和描述", 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": "模式名称(默认为dbo)", "default": "", }, "database_key": map[string]interface{}{ "type": "string", "description": "数据库配置键名(如:business),可选,默认使用主数据库", "enum": []string{"warehouse", "business"}, "default": "warehouse", }, }, "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 } // 获取数据库类型,确保是SQL Server dbType := dbFactory.GetDBType() if dbType != "sqlserver" { return nil, fmt.Errorf("当前数据库类型为 %s,此工具仅支持SQL Server数据库", dbType) } // 设置默认模式 schema := strings.TrimSpace(params.Schema) if schema == "" { schema = "dbo" } // 构建查询SQL var query string if params.IncludeSystemTables { query = ` SELECT TABLE_SCHEMA as schema_name, TABLE_NAME as table_name, '' as table_description -- SQL Server没有内置的表描述字段 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA = @p1 ORDER BY TABLE_NAME` } else { query = ` SELECT TABLE_SCHEMA as schema_name, TABLE_NAME as table_name, '' as table_description -- SQL Server没有内置的表描述字段 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA = @p1 AND TABLE_NAME NOT LIKE 'sys%' AND TABLE_NAME NOT LIKE 'MS%' ORDER BY TABLE_NAME` } // 执行查询 results, err := dbFactory.QuerySliceMapWithParams(query, schema) if err != nil { return nil, fmt.Errorf("查询表信息失败: %v", err) } // SQL Server没有内置表描述,尝试从扩展属性获取 for i := range results { tableName := results[i]["table_name"].(string) descQuery := ` SELECT value as table_description FROM fn_listextendedproperty ('MS_Description', 'SCHEMA', @p1, 'TABLE', @p2, NULL, NULL)` descResults, err := dbFactory.QuerySliceMapWithParams(descQuery, schema, tableName) if err == nil && len(descResults) > 0 { if desc, ok := descResults[0]["table_description"].(string); ok && desc != "" { results[i]["table_description"] = desc } } } 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), "note": "SQL Server表描述需要手动通过扩展属性设置", }, nil }, ) }