|
| 1 | +// Copyright 2025 Dolthub, Inc. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package sqlserver |
| 16 | + |
| 17 | +import ( |
| 18 | + "context" |
| 19 | + "net" |
| 20 | + "strconv" |
| 21 | + |
| 22 | + "github.com/sirupsen/logrus" |
| 23 | + "go.uber.org/zap" |
| 24 | + "go.uber.org/zap/zapcore" |
| 25 | + "golang.org/x/sync/errgroup" |
| 26 | + |
| 27 | + pkgmcp "github.com/dolthub/dolt-mcp/mcp/pkg" |
| 28 | + mcpdb "github.com/dolthub/dolt-mcp/mcp/pkg/db" |
| 29 | + "github.com/dolthub/dolt-mcp/mcp/pkg/toolsets" |
| 30 | + "github.com/dolthub/dolt/go/libraries/utils/svcs" |
| 31 | +) |
| 32 | + |
| 33 | +// MCPConfig encapsulates MCP-specific configuration for the sql-server |
| 34 | +type MCPConfig struct { |
| 35 | + Port *int |
| 36 | + User *string |
| 37 | + Password *string |
| 38 | + Database *string |
| 39 | +} |
| 40 | + |
| 41 | +// logrusZapCore implements a zapcore.Core that forwards entries to a logrus.Logger |
| 42 | +type logrusZapCore struct { |
| 43 | + l *logrus.Logger |
| 44 | + prefix string |
| 45 | +} |
| 46 | + |
| 47 | +func newZapFromLogrusWithPrefix(l *logrus.Logger, prefix string) *zap.Logger { |
| 48 | + core := &logrusZapCore{l: l, prefix: prefix} |
| 49 | + return zap.New(core, zap.AddCallerSkip(1)) |
| 50 | +} |
| 51 | + |
| 52 | +func (c *logrusZapCore) With(fields []zapcore.Field) zapcore.Core { |
| 53 | + // zap will call Write with fields; we don't need to carry state here |
| 54 | + return c |
| 55 | +} |
| 56 | + |
| 57 | +func (c *logrusZapCore) Enabled(lvl zapcore.Level) bool { |
| 58 | + // Respect logrus current level |
| 59 | + return zapToLogrusLevel(lvl) >= c.l.GetLevel() |
| 60 | +} |
| 61 | + |
| 62 | +func (c *logrusZapCore) Check(ent zapcore.Entry, ce *zapcore.CheckedEntry) *zapcore.CheckedEntry { |
| 63 | + if c.Enabled(ent.Level) { |
| 64 | + return ce.AddCore(ent, c) |
| 65 | + } |
| 66 | + return ce |
| 67 | +} |
| 68 | + |
| 69 | +func (c *logrusZapCore) Write(ent zapcore.Entry, fields []zapcore.Field) error { |
| 70 | + enc := zapcore.NewMapObjectEncoder() |
| 71 | + for _, f := range fields { |
| 72 | + f.AddTo(enc) |
| 73 | + } |
| 74 | + // Build fields map |
| 75 | + lf := logrus.Fields(enc.Fields) |
| 76 | + msg := c.prefix + ent.Message |
| 77 | + c.l.WithFields(lf).Log(zapToLogrusLevel(ent.Level), msg) |
| 78 | + return nil |
| 79 | +} |
| 80 | + |
| 81 | +func (c *logrusZapCore) Sync() error { return nil } |
| 82 | + |
| 83 | +func zapToLogrusLevel(l zapcore.Level) logrus.Level { |
| 84 | + switch l { |
| 85 | + case zapcore.DebugLevel: |
| 86 | + return logrus.DebugLevel |
| 87 | + case zapcore.InfoLevel: |
| 88 | + return logrus.InfoLevel |
| 89 | + case zapcore.WarnLevel: |
| 90 | + return logrus.WarnLevel |
| 91 | + case zapcore.ErrorLevel: |
| 92 | + return logrus.ErrorLevel |
| 93 | + case zapcore.DPanicLevel, zapcore.PanicLevel, zapcore.FatalLevel: |
| 94 | + return logrus.FatalLevel |
| 95 | + default: |
| 96 | + return logrus.InfoLevel |
| 97 | + } |
| 98 | +} |
| 99 | + |
| 100 | +// mcpInit validates and reserves the MCP port |
| 101 | +func mcpInit(cfg *Config, state *svcs.ServiceState) func(context.Context) error { |
| 102 | + return func(context.Context) error { |
| 103 | + addr := net.JoinHostPort("0.0.0.0", strconv.Itoa(*cfg.MCP.Port)) |
| 104 | + l, err := net.Listen("tcp", addr) |
| 105 | + if err != nil { |
| 106 | + return err |
| 107 | + } |
| 108 | + _ = l.Close() |
| 109 | + state.Swap(svcs.ServiceState_Init) |
| 110 | + return nil |
| 111 | + } |
| 112 | +} |
| 113 | + |
| 114 | +// mcpRun starts the MCP HTTP server and wires lifecycle to errgroup |
| 115 | +func mcpRun(cfg *Config, lgr *logrus.Logger, state *svcs.ServiceState, cancelPtr *context.CancelFunc, groupPtr **errgroup.Group) func(context.Context) { |
| 116 | + return func(ctx context.Context) { |
| 117 | + if !state.CompareAndSwap(svcs.ServiceState_Init, svcs.ServiceState_Run) { |
| 118 | + return |
| 119 | + } |
| 120 | + |
| 121 | + // Logger for MCP (prefix and level inherited from logrus) |
| 122 | + logger := newZapFromLogrusWithPrefix(lgr, "[dolt-mcp] ") |
| 123 | + |
| 124 | + if cfg.MCP.User == nil || *cfg.MCP.User == "" { |
| 125 | + lgr.WithField("component", "dolt-mcp").Error("MCP user not defined") |
| 126 | + return |
| 127 | + } |
| 128 | + |
| 129 | + // Build DB config |
| 130 | + password := "" |
| 131 | + if cfg.MCP.Password != nil { |
| 132 | + password = *cfg.MCP.Password |
| 133 | + } |
| 134 | + dbName := "" |
| 135 | + if cfg.MCP.Database != nil { |
| 136 | + dbName = *cfg.MCP.Database |
| 137 | + } |
| 138 | + dbConf := mcpdb.Config{ |
| 139 | + Host: "127.0.0.1", |
| 140 | + Port: cfg.ServerConfig.Port(), |
| 141 | + User: *cfg.MCP.User, |
| 142 | + Password: password, |
| 143 | + DatabaseName: dbName, |
| 144 | + } |
| 145 | + |
| 146 | + srv, err := pkgmcp.NewMCPHTTPServer( |
| 147 | + logger, |
| 148 | + dbConf, |
| 149 | + *cfg.MCP.Port, |
| 150 | + toolsets.WithToolSet(&toolsets.PrimitiveToolSetV1{}), |
| 151 | + ) |
| 152 | + if err != nil { |
| 153 | + lgr.WithField("component", "dolt-mcp").Errorf("failed to start Dolt MCP HTTP server: %v", err) |
| 154 | + return |
| 155 | + } |
| 156 | + |
| 157 | + runCtx, cancel := context.WithCancel(ctx) |
| 158 | + *cancelPtr = cancel |
| 159 | + g, gctx := errgroup.WithContext(runCtx) |
| 160 | + g.Go(func() error { srv.ListenAndServe(gctx); return nil }) |
| 161 | + *groupPtr = g |
| 162 | + } |
| 163 | +} |
| 164 | + |
| 165 | +// mcpStop gracefully stops the MCP server by cancelling context and waiting for the errgroup |
| 166 | +func mcpStop(cancel context.CancelFunc, group *errgroup.Group, state *svcs.ServiceState) func() error { |
| 167 | + return func() error { |
| 168 | + if cancel != nil { |
| 169 | + cancel() |
| 170 | + } |
| 171 | + if group != nil { |
| 172 | + if err := group.Wait(); err != nil { |
| 173 | + return err |
| 174 | + } |
| 175 | + } |
| 176 | + state.Swap(svcs.ServiceState_Stopped) |
| 177 | + return nil |
| 178 | + } |
| 179 | +} |
| 180 | + |
| 181 | +// registerMCPService wires the MCP service into the controller using helper funcs |
| 182 | +func registerMCPService(controller *svcs.Controller, cfg *Config, lgr *logrus.Logger) { |
| 183 | + if cfg.MCP == nil || cfg.MCP.Port == nil || *cfg.MCP.Port <= 0 { |
| 184 | + return |
| 185 | + } |
| 186 | + var state svcs.ServiceState |
| 187 | + var cancel context.CancelFunc |
| 188 | + var group *errgroup.Group |
| 189 | + |
| 190 | + svc := &svcs.AnonService{ |
| 191 | + InitF: mcpInit(cfg, &state), |
| 192 | + RunF: mcpRun(cfg, lgr, &state, &cancel, &group), |
| 193 | + StopF: mcpStop(cancel, group, &state), |
| 194 | + } |
| 195 | + _ = controller.Register(svc) |
| 196 | +} |
0 commit comments