Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@
- 目标数据库:MySQL + PostgreSQL。
- 可扩展性:通过 driver registry 扩展新 DB。
- **默认只读**:防止误操作,默认启用双重只读保护(SQL 静态分析 + 数据库事务级只读)。
- **CLI 写入双重授权**:profile 必须配置 `unsafe_allow_write: true`,且当前 `query` 命令必须同时携带 `--unsafe-allow-write`;任一条件缺失都保持只读。
- **CLI / MCP 写入双重授权**:profile 必须配置 `unsafe_allow_write: true`,且当前 `query` 命令或 `mcp server` 必须同时携带 `--unsafe-allow-write`(或 `XSQL_MCP_UNSAFE_ALLOW_WRITE=true`);任一条件缺失都保持只读。Web 始终强制只读。
- **AI 调用标记**:Codex 发起的 xsql CLI 调用必须携带 `--attr source=codex-cli`,建议同时追加 `agent`、`env`、`team`、`task` 等 attr;其他 AI 客户端应使用自己的稳定 source 值,且不得覆盖 source。
- 只读拦截必须返回明确错误码(退出码=4)。

Expand Down
40 changes: 26 additions & 14 deletions cmd/xsql/mcp.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ func runMCPServer(opts *mcpServerOptions) error {
// Load config
cfg, _, xe := config.LoadConfig(config.Options{
ConfigPath: GlobalConfig.ConfigStr,
WorkDir: os.Getenv("XSQL_WORKDIR"),
HomeDir: os.Getenv("XSQL_HOMEDIR"),
})
if xe != nil {
return xe
Expand All @@ -74,6 +76,7 @@ func runMCPServer(opts *mcpServerOptions) error {

server, err := mcp_pkg.CreateServer(version, &cfg, GlobalConfig.Stats, mcp_pkg.ServerOptions{
UnsafeAllowWrite: resolved.unsafeAllowWrite,
Attrs: GlobalConfig.Attrs,
})
if err != nil {
if xe, ok := err.(*errors.XError); ok {
Expand All @@ -90,10 +93,13 @@ func runMCPServer(opts *mcpServerOptions) error {

sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
defer signal.Stop(sigChan)
go func() {
<-sigChan
signal.Stop(sigChan)
cancel()
select {
case <-sigChan:
cancel()
case <-ctx.Done():
}
}()

if err := runMCPStdioServer(ctx, server); err != nil && !stderrors.Is(err, context.Canceled) {
Expand All @@ -109,23 +115,29 @@ func runMCPServer(opts *mcpServerOptions) error {
return errors.Wrap(errors.CodeInternal, "failed to create streamable http handler", nil, err)
}
httpServer := &http.Server{
Addr: resolved.httpAddr,
Handler: handler,
ReadTimeout: 30 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 120 * time.Second,
Addr: resolved.httpAddr,
Handler: handler,
ReadHeaderTimeout: 15 * time.Second,
ReadTimeout: 30 * time.Second,
WriteTimeout: 120 * time.Second,
IdleTimeout: 120 * time.Second,
}

sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
defer signal.Stop(sigChan)
done := make(chan struct{})
defer close(done)

go func() {
<-sigChan
signal.Stop(sigChan)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if shutdownErr := httpServer.Shutdown(ctx); shutdownErr != nil {
log.Printf("[mcp] http server shutdown error: %v", shutdownErr)
select {
case <-sigChan:
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if shutdownErr := httpServer.Shutdown(ctx); shutdownErr != nil {
log.Printf("[mcp] http server shutdown error: %v", shutdownErr)
}
case <-done:
}
}()

Expand Down
59 changes: 25 additions & 34 deletions cmd/xsql/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"os"
"strconv"

"github.com/spf13/cobra"

Expand Down Expand Up @@ -38,34 +39,6 @@ func NewRootCommand() *cobra.Command {
Use: "xsql",
SilenceUsage: true,
SilenceErrors: true,
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
// CLI > ENV > Config
formatSet := cmd.Flags().Changed("format")
profileSet := cmd.Flags().Changed("profile")
configSet := cmd.Flags().Changed("config")
if configSet && GlobalConfig.ConfigStr == "" {
return errors.New(errors.CodeCfgInvalid, "config path is empty", nil)
}

r, xe := config.Resolve(config.Options{
ConfigPath: GlobalConfig.ConfigStr,
CLIProfile: GlobalConfig.ProfileStr,
CLIProfileSet: profileSet,
CLIFormat: GlobalConfig.FormatStr,
CLIFormatSet: formatSet,
EnvProfile: os.Getenv("XSQL_PROFILE"),
EnvFormat: os.Getenv("XSQL_FORMAT"),
WorkDir: os.Getenv("XSQL_WORKDIR"),
HomeDir: os.Getenv("XSQL_HOMEDIR"),
})
if xe != nil {
return xe
}
GlobalConfig.Resolved = r
GlobalConfig.FormatStr = r.Format
GlobalConfig.ProfileStr = r.ProfileName
return nil
},
}

var cliAttrs []string
Expand Down Expand Up @@ -104,8 +77,11 @@ func NewRootCommand() *cobra.Command {

// Parse attributes: CLI > ENV
GlobalConfig.Attrs = stats.ParseAttrs(cliAttrs, stats.GetXSQLAttrEnv())
if err := stats.ValidateAttrs(GlobalConfig.Attrs); err != nil {
return errors.Wrap(errors.CodeCfgInvalid, err.Error(), nil, err)
}

// Load stats config from file
// Load stats config from file + ENV overrides
GlobalConfig.Stats = loadStatsConfig(GlobalConfig.ConfigStr)

return nil
Expand All @@ -114,11 +90,26 @@ func NewRootCommand() *cobra.Command {
return root
}

// loadStatsConfig loads stats configuration from the config file.
// loadStatsConfig loads stats configuration from the config file and applies environment overrides.
func loadStatsConfig(configPath string) stats.StatsConfig {
cfg, _, xe := config.LoadConfig(config.Options{ConfigPath: configPath})
if xe != nil {
return stats.StatsConfig{}
var st stats.StatsConfig
cfg, _, xe := config.LoadConfig(config.Options{
ConfigPath: configPath,
WorkDir: os.Getenv("XSQL_WORKDIR"),
HomeDir: os.Getenv("XSQL_HOMEDIR"),
})
if xe == nil {
st = cfg.Stats
}
if envEnabled := os.Getenv("XSQL_STATS_ENABLED"); envEnabled != "" {
if parsed, err := strconv.ParseBool(envEnabled); err == nil {
st.Enabled = parsed
}
}
if envLogSQL := os.Getenv("XSQL_STATS_LOG_SQL"); envLogSQL != "" {
if parsed, err := strconv.ParseBool(envLogSQL); err == nil {
st.LogSQL = parsed
}
}
return cfg.Stats
return st
}
48 changes: 37 additions & 11 deletions cmd/xsql/stats.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
}

cmd.Flags().StringVarP(&flags.Profile, "profile", "p", "", "Filter by profile name")
cmd.Flags().BoolVar(&flags.JSON, "json", false, "Output as JSON")

Check failure on line 41 in cmd/xsql/stats.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Define a constant instead of duplicating this literal "Output as JSON" 3 times.

See more on https://sonarcloud.io/project/issues?id=zx06_xsql&issues=AaGwgYjih-6FesL3Y_xG&open=AaGwgYjih-6FesL3Y_xG&pullRequest=88

// Add subcommands
cmd.AddCommand(newStatsLogCommand(w))
Expand All @@ -47,7 +47,22 @@
return cmd
}

func resolveStatsFormat(jsonFlag bool) (output.Format, error) {
if jsonFlag {
return output.FormatJSON, nil
}
if GlobalConfig.FormatStr != "" && GlobalConfig.FormatStr != string(output.FormatAuto) {
return parseOutputFormat(GlobalConfig.FormatStr)
}
return output.FormatTable, nil
}

func runStats(flags *StatsFlags, w *output.Writer) error {
format, err := resolveStatsFormat(flags.JSON)
if err != nil {
return err
}

store := stats.NewStore(GlobalConfig.Stats.FilePath)
records, err := store.Load()
if err != nil {
Expand All @@ -61,11 +76,6 @@

agg := stats.Query(records, filter)

format := output.FormatTable
if flags.JSON {
format = output.FormatJSON
}

return w.WriteOK(format, &stats.StatsResult{Records: agg})
}

Expand All @@ -88,6 +98,11 @@
}

func runStatsLog(flags *StatsLogFlags, w *output.Writer) error {
format, err := resolveStatsFormat(flags.JSON)
if err != nil {
return err
}

store := stats.NewStore(GlobalConfig.Stats.FilePath)
records, err := store.Load()
if err != nil {
Expand Down Expand Up @@ -116,25 +131,33 @@
result[i] = *r
}

format := output.FormatTable
if flags.JSON {
format = output.FormatJSON
}

return w.WriteOK(format, &stats.LogResult{
Records: result,
Total: len(records),
})
}

func newStatsResetCommand(w *output.Writer) *cobra.Command {
return &cobra.Command{
var jsonFlag bool
cmd := &cobra.Command{
Use: "reset",
Short: "Reset usage statistics",
RunE: func(cmd *cobra.Command, args []string) error {
if jsonFlag || (GlobalConfig.FormatStr != "" && GlobalConfig.FormatStr != string(output.FormatAuto)) {
format, err := resolveStatsFormat(jsonFlag)
if err != nil {
return err
}
if err := runStatsReset(w); err != nil {
return err
}
return w.WriteOK(format, map[string]any{"reset": true})
}
return runStatsReset(w)
},
}
cmd.Flags().BoolVar(&jsonFlag, "json", false, "Output as JSON")
return cmd
}

func runStatsReset(w *output.Writer) error {
Expand Down Expand Up @@ -173,4 +196,7 @@

// Best-effort: don't fail the command if stats recording fails
_ = store.Append(r)
if GlobalConfig.Stats.RetentionDays > 0 {
_, _ = store.Cleanup(GlobalConfig.Stats.RetentionDays)
}
}
49 changes: 49 additions & 0 deletions cmd/xsql/stats_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -347,3 +347,52 @@ func TestNewStatsResetCommand(t *testing.T) {
t.Error("expected stats file to be removed")
}
}

func TestStatsFormatAndRetentionCleanup(t *testing.T) {
dir := t.TempDir()
statsPath := filepath.Join(dir, "stats.jsonl")
GlobalConfig.Stats.FilePath = statsPath
GlobalConfig.Stats.RetentionDays = 7
defer func() {
GlobalConfig.Stats.RetentionDays = 0
GlobalConfig.FormatStr = "auto"
}()

store := stats.NewStore(statsPath)
_ = store.Append(&stats.Record{
Timestamp: time.Now(),
Cmd: "query",
Profile: "dev",
OK: true,
DurationMs: 12,
})

for _, fmtStr := range []string{"json", "yaml"} {
GlobalConfig.FormatStr = fmtStr
var buf bytes.Buffer
w := output.New(&buf, &buf)
if err := runStats(&StatsFlags{}, &w); err != nil {
t.Fatalf("runStats(%s): %v", fmtStr, err)
}
if err := runStatsLog(&StatsLogFlags{Limit: 10}, &w); err != nil {
t.Fatalf("runStatsLog(%s): %v", fmtStr, err)
}
}
}

func TestLoadStatsConfigEnvVars(t *testing.T) {
dir := t.TempDir()
t.Setenv("XSQL_WORKDIR", dir)
t.Setenv("XSQL_HOMEDIR", dir)
t.Setenv("XSQL_STATS_ENABLED", "1")
t.Setenv("XSQL_STATS_LOG_SQL", "true")
st := loadStatsConfig("")
if !st.Enabled || !st.LogSQL {
t.Fatalf("expected stats enabled and log_sql true from env, got %+v", st)
}
GlobalConfig.Stats = st
GlobalConfig.Stats.FilePath = filepath.Join(dir, "stats.jsonl")
GlobalConfig.Stats.RetentionDays = 7
recordCmdStats("query", "dev", true, 5*time.Millisecond, "", "SELECT 1")
GlobalConfig.Stats.RetentionDays = 0
}
3 changes: 2 additions & 1 deletion cmd/xsql/web.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ func runWebCommand(opts *webCommandOptions, w *output.Writer) error {
AuthRequired: resolved.authRequired,
AuthToken: resolved.authToken,
Stats: GlobalConfig.Stats,
Attrs: GlobalConfig.Attrs,
})
server := webpkg.NewServer(listener, handler)
url := webpkg.PublicURL(server.Addr())
Expand Down Expand Up @@ -187,7 +188,7 @@ func resolveWebOptions(opts *webCommandOptions, cfg config.File) (resolvedWebOpt
authToken = secretValue
}

authRequired := !webpkg.IsLoopbackAddr(addr)
authRequired := !webpkg.IsLoopbackAddr(addr) || authToken != ""
if authRequired && authToken == "" {
return resolvedWebOptions{}, errors.New(errors.CodeCfgInvalid, "web auth token is required for non-loopback addresses", map[string]any{"addr": addr})
}
Expand Down
5 changes: 3 additions & 2 deletions docs/architecture.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# 架构设计(Architecture)

## 分层原则
- 核心能力(config/db/ssh/output)与 CLI 解耦,便于未来扩展 MCP/TUI/Web。
- 核心能力(config/db/ssh/output)与 CLI 解耦,便于扩展 MCP/Web。
- 输出与错误遵循稳定契约,优先保证 AI/agent 可消费。

## 建议目录结构
Expand All @@ -27,6 +27,7 @@
## 关键扩展点
- DB driver:通过 registry 注册,实现新数据库无需改动核心逻辑。
- 输出 formatter:通过接口注册新格式。
- Frontend:CLI/MCP/TUI/Web 仅是调用 `internal/app` 的不同适配层。
- Frontend:CLI/MCP/Web 仅是调用 `internal/app` 的不同适配层。
- MCP:`internal/mcp` 注册 MCP tools,数据库与 schema 操作经 `internal/app`(与 Web 相同),不重复实现连接/SSH。
- Web:本地 HTTP server 与嵌入式前端通过 `internal/web` 适配,复用 `internal/app` 业务服务。

6 changes: 4 additions & 2 deletions docs/cli-spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ xsql schema dump -p dev --include-system
| `--include-system` | false | 包含系统表 |
| `--allow-plaintext` | false | 允许配置中使用明文密码 |
| `--ssh-skip-known-hosts-check` | false | 跳过 SSH 主机密钥验证(危险) |
| `--schema-timeout` | 60 | Schema 导出超时(秒);profile 可用 `schema_timeout` 覆盖 |

**输出示例(JSON):**
```json
Expand Down Expand Up @@ -492,8 +493,9 @@ xsql config set ssh_proxy.bastion.user admin
| Flag | 说明 |
|------|------|
| `--config <path>` | 指定 YAML 配置文件路径 |
| `--profile <name>` | 选择 profile(等价 ENV:`XSQL_PROFILE`) |
| `--format <fmt>` | 输出格式(等价 ENV:`XSQL_FORMAT`) |
| `-p, --profile <name>` | 选择 profile(等价 ENV:`XSQL_PROFILE`) |
| `-f, --format <fmt>` | 输出格式(等价 ENV:`XSQL_FORMAT`) |
| `--attr <key=value>` | 标记会话属性(可重复,等价 ENV:`XSQL_ATTR`) |

## 格式说明

Expand Down
5 changes: 3 additions & 2 deletions docs/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,15 +155,16 @@ Profile 还可设置 `max_rows`(query 默认行数上限,CLI/Web 默认 1000
| `user` | string | 数据库用户名 |
| `password` | string | 密码(支持 `keyring:` 引用) |
| `database` | string | 数据库名 |
| `unsafe_allow_write` | bool | 允许该 profile 进入写模式(默认 false);CLI 仍需本次命令携带 `--unsafe-allow-write` |
| `unsafe_allow_write` | bool | 允许该 profile 进入写模式(默认 false);CLI/MCP 仍需同时携带 `--unsafe-allow-write`(或 `XSQL_MCP_UNSAFE_ALLOW_WRITE=true`) |
| `allow_plaintext` | bool | 允许明文密码(默认 false) |
| `format` | string | 输出格式:json/yaml/table/csv/auto |
| `local_port` | int | proxy 本地监听端口(默认 0,自动分配) |
| `ssh_proxy` | string | SSH 代理名称(引用 `ssh_proxies` 中定义的名称) |
| `query_timeout` | int | 查询超时秒数(默认 30 秒) |
| `schema_timeout` | int | Schema 导出超时秒数(默认 60 秒) |
| `max_rows` | int | 查询默认返回行数上限(CLI/Web 默认 1000,MCP 默认 500) |

> **CLI 写入双重授权**:`xsql query` 只有在所选 profile 配置 `unsafe_allow_write: true` 且当前命令同时携带 `--unsafe-allow-write` 时才会绕过只读保护。配置或 flag 单独开启都不会允许 CLI 写入。MCP 仍由 profile 配置控制,Web 始终只读。
> **CLI / MCP 写入双重授权**:`xsql query` 与 `xsql mcp server` 只有在所选 profile 配置 `unsafe_allow_write: true` 且当前运行入口同时携带 `--unsafe-allow-write`(MCP 也支持 `XSQL_MCP_UNSAFE_ALLOW_WRITE=true`)时才会绕过只读保护。配置或运行时开关单独开启都不会允许写入。Web 始终强制只读。

## Stats 配置项

Expand Down
Loading
Loading