-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathserver.go
More file actions
176 lines (145 loc) · 4.76 KB
/
server.go
File metadata and controls
176 lines (145 loc) · 4.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
package mcp
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"time"
"github.com/modelcontextprotocol/go-sdk/mcp"
"go.uber.org/zap"
"github.com/timescale/tiger-cli/internal/tiger/analytics"
"github.com/timescale/tiger-cli/internal/tiger/api"
"github.com/timescale/tiger-cli/internal/tiger/config"
"github.com/timescale/tiger-cli/internal/tiger/logging"
)
const (
ServerName = "tiger"
serverTitle = "Tiger MCP"
)
// Server wraps the MCP server with Tiger-specific functionality
type Server struct {
mcpServer *mcp.Server
docsProxyClient *ProxyClient
}
// NewServer creates a new Tiger MCP server instance
func NewServer(ctx context.Context) (*Server, error) {
// Create MCP server
mcpServer := mcp.NewServer(&mcp.Implementation{
Name: ServerName,
Title: serverTitle,
Version: config.Version,
}, nil)
server := &Server{
mcpServer: mcpServer,
}
// Register all tools (including proxied docs tools)
server.registerTools(ctx)
// Add analytics tracking middleware
server.mcpServer.AddReceivingMiddleware(server.analyticsMiddleware)
return server, nil
}
// Run starts the MCP server with the stdio transport
func (s *Server) StartStdio(ctx context.Context) error {
return s.mcpServer.Run(ctx, &mcp.StdioTransport{})
}
// Returns an HTTP handler that implements the http transport
func (s *Server) HTTPHandler() http.Handler {
return mcp.NewStreamableHTTPHandler(func(req *http.Request) *mcp.Server {
return s.mcpServer
}, &mcp.StreamableHTTPOptions{
Stateless: true,
})
}
// registerTools registers all available MCP tools
func (s *Server) registerTools(ctx context.Context) {
// Service management tools
s.registerServiceTools()
// Database operation tools
s.registerDatabaseTools()
// TODO: Register more tool groups
// Register remote docs MCP server proxy
s.registerDocsProxy(ctx)
logging.Info("MCP tools registered successfully")
}
// createAPIClient creates a new API client and returns it with the project ID
func (s *Server) createAPIClient() (*api.ClientWithResponses, string, error) {
// Load config
cfg, err := config.Load()
if err != nil {
return nil, "", fmt.Errorf("failed to load config: %w", err)
}
// Get credentials (API key + project ID)
apiKey, projectID, err := config.GetCredentials()
if err != nil {
return nil, "", fmt.Errorf("authentication required: %w. Please run 'tiger auth login'", err)
}
// Create API client with fresh credentials
apiClient, err := api.NewTigerClient(cfg, apiKey)
if err != nil {
return nil, "", fmt.Errorf("failed to create API client: %w", err)
}
return apiClient, projectID, nil
}
// analyticsMiddleware tracks analytics for all MCP requests
func (s *Server) analyticsMiddleware(next mcp.MethodHandler) mcp.MethodHandler {
return func(ctx context.Context, method string, req mcp.Request) (result mcp.Result, runErr error) {
start := time.Now()
// Load config for analytics
cfg, err := config.Load()
if err != nil {
// If we can't load config, just skip analytics and continue
return next(ctx, method, req)
}
a := analytics.TryInit(cfg)
switch r := req.(type) {
case *mcp.CallToolRequest:
// Extract arguments from the tool call
var args map[string]any
if len(r.Params.Arguments) > 0 {
if err := json.Unmarshal(r.Params.Arguments, &args); err != nil {
logging.Error("Error unmarshaling tool call arguments", zap.Error(err))
}
}
defer func() {
toolErr := runErr
if callToolResult, ok := result.(*mcp.CallToolResult); ok && callToolResult != nil && callToolResult.IsError && len(callToolResult.Content) > 0 {
if textContent, ok := callToolResult.Content[0].(*mcp.TextContent); ok && textContent != nil {
toolErr = errors.New(textContent.Text)
}
}
a.Track(fmt.Sprintf("Call %s tool", r.Params.Name),
analytics.Map(args),
analytics.Property("elapsed_seconds", time.Since(start).Seconds()),
analytics.Error(toolErr),
)
}()
case *mcp.ReadResourceRequest:
defer func() {
a.Track("Read proxied resource",
analytics.Property("resource_uri", r.Params.URI),
analytics.Property("elapsed_seconds", time.Since(start).Seconds()),
analytics.Error(runErr),
)
}()
case *mcp.GetPromptRequest:
defer func() {
a.Track(fmt.Sprintf("Get %s prompt", r.Params.Name),
analytics.Property("elapsed_seconds", time.Since(start).Seconds()),
analytics.Error(runErr),
)
}()
}
// Execute the actual handler
return next(ctx, method, req)
}
}
// Close gracefully shuts down the MCP server and all proxy connections
func (s *Server) Close() error {
logging.Debug("Closing MCP server and proxy connections")
// Close docs proxy connection
if err := s.docsProxyClient.Close(); err != nil {
return fmt.Errorf("failed to close docs proxy client: %w", err)
}
return nil
}