blob: 7ea74a6d4dc172b76aade25de8b1f005162c3a89 [file] [log] [blame]
Philip Zeyliger194bfa82025-06-24 06:03:06 -07001package mcp
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "log/slog"
8 "strings"
9 "sync"
10 "time"
11
12 "github.com/mark3labs/mcp-go/client"
13 "github.com/mark3labs/mcp-go/client/transport"
14 "github.com/mark3labs/mcp-go/mcp"
15 "sketch.dev/llm"
16)
17
18// ServerConfig represents the configuration for an MCP server
19type ServerConfig struct {
20 Name string `json:"name,omitempty"`
21 Type string `json:"type,omitempty"` // "stdio", "http", "sse"
22 URL string `json:"url,omitempty"` // for http/sse
23 Command string `json:"command,omitempty"` // for stdio
24 Args []string `json:"args,omitempty"` // for stdio
25 Env map[string]string `json:"env,omitempty"` // for stdio
26 Headers map[string]string `json:"headers,omitempty"` // for http/sse
27}
28
29// MCPManager manages multiple MCP server connections
30type MCPManager struct {
31 mu sync.RWMutex
32 clients map[string]*MCPClientWrapper
33}
34
35// MCPClientWrapper wraps an MCP client connection
36type MCPClientWrapper struct {
37 name string
38 config ServerConfig
39 client *client.Client
40 tools []*llm.Tool
41}
42
43// MCPServerConnection represents a successful MCP server connection with its tools
44type MCPServerConnection struct {
45 ServerName string
46 Tools []*llm.Tool
47 ToolNames []string // Original tool names without server prefix
48}
49
50// NewMCPManager creates a new MCP manager
51func NewMCPManager() *MCPManager {
52 return &MCPManager{
53 clients: make(map[string]*MCPClientWrapper),
54 }
55}
56
57// ParseServerConfigs parses JSON configuration strings into ServerConfig structs
58func ParseServerConfigs(ctx context.Context, configs []string) ([]ServerConfig, []error) {
59 if len(configs) == 0 {
60 return nil, nil
61 }
62
63 var serverConfigs []ServerConfig
64 var errors []error
65
66 for i, configStr := range configs {
67 var config ServerConfig
68 if err := json.Unmarshal([]byte(configStr), &config); err != nil {
69 slog.ErrorContext(ctx, "Failed to parse MCP server config", "config", configStr, "error", err)
70 errors = append(errors, fmt.Errorf("config %d: %w", i, err))
71 continue
72 }
73 // Require a name
74 if config.Name == "" {
75 errors = append(errors, fmt.Errorf("config %d: name is required", i))
76 continue
77 }
78 serverConfigs = append(serverConfigs, config)
79 }
80
81 return serverConfigs, errors
82}
83
Philip Zeyliger4201bde2025-06-27 17:22:43 -070084// ConnectToServerConfigs connects to multiple parsed MCP server configs in parallel
Philip Zeyliger194bfa82025-06-24 06:03:06 -070085func (m *MCPManager) ConnectToServerConfigs(ctx context.Context, serverConfigs []ServerConfig, timeout time.Duration, existingErrors []error) ([]MCPServerConnection, []error) {
86 if len(serverConfigs) == 0 {
87 return nil, existingErrors
88 }
89
90 slog.InfoContext(ctx, "Connecting to MCP servers", "count", len(serverConfigs), "timeout", timeout)
91
92 // Connect to servers in parallel using sync.WaitGroup
93 type result struct {
94 tools []*llm.Tool
95 err error
96 serverName string
97 originalTools []string // Original tool names without server prefix
98 }
99
100 results := make(chan result, len(serverConfigs))
101 ctxWithTimeout, cancel := context.WithTimeout(ctx, timeout)
102 defer cancel()
103
104 for _, config := range serverConfigs {
105 go func(cfg ServerConfig) {
106 slog.InfoContext(ctx, "Connecting to MCP server", "server", cfg.Name, "type", cfg.Type, "url", cfg.URL, "command", cfg.Command)
107 tools, originalToolNames, err := m.connectToServerWithNames(ctxWithTimeout, cfg)
108 results <- result{
109 tools: tools,
110 err: err,
111 serverName: cfg.Name,
112 originalTools: originalToolNames,
113 }
114 }(config)
115 }
116
117 // Collect results
118 var connections []MCPServerConnection
119 errors := make([]error, 0, len(existingErrors))
120 errors = append(errors, existingErrors...)
121
122 for range len(serverConfigs) {
123 select {
124 case res := <-results:
125 if res.err != nil {
126 slog.ErrorContext(ctx, "Failed to connect to MCP server", "server", res.serverName, "error", res.err)
127 errors = append(errors, fmt.Errorf("MCP server %q: %w", res.serverName, res.err))
128 } else {
129 connection := MCPServerConnection{
130 ServerName: res.serverName,
131 Tools: res.tools,
132 ToolNames: res.originalTools,
133 }
134 connections = append(connections, connection)
135 slog.InfoContext(ctx, "Successfully connected to MCP server", "server", res.serverName, "tools", len(res.tools), "tool_names", res.originalTools)
136 }
137 case <-ctxWithTimeout.Done():
138 errors = append(errors, fmt.Errorf("timeout connecting to MCP servers"))
139 break
140 }
141 }
142
143 return connections, errors
144}
145
146// connectToServerWithNames connects to a single MCP server and returns tools with original names
147func (m *MCPManager) connectToServerWithNames(ctx context.Context, config ServerConfig) ([]*llm.Tool, []string, error) {
148 tools, err := m.connectToServer(ctx, config)
149 if err != nil {
150 return nil, nil, err
151 }
152
153 // Extract original tool names (remove server prefix)
154 originalNames := make([]string, len(tools))
155 for i, tool := range tools {
156 // Tool names are in format "servername_toolname"
157 parts := strings.SplitN(tool.Name, "_", 2)
158 if len(parts) == 2 {
159 originalNames[i] = parts[1]
160 } else {
161 originalNames[i] = tool.Name // fallback if no prefix
162 }
163 }
164
165 return tools, originalNames, nil
166}
167
168// connectToServer connects to a single MCP server
169func (m *MCPManager) connectToServer(ctx context.Context, config ServerConfig) ([]*llm.Tool, error) {
170 var mcpClient *client.Client
171 var err error
172
173 // Convert environment variables to []string format
174 var envVars []string
175 for k, v := range config.Env {
176 envVars = append(envVars, k+"="+v)
177 }
178
179 switch config.Type {
180 case "stdio", "":
181 if config.Command == "" {
182 return nil, fmt.Errorf("command is required for stdio transport")
183 }
184 mcpClient, err = client.NewStdioMCPClient(config.Command, envVars, config.Args...)
185 case "http":
186 if config.URL == "" {
187 return nil, fmt.Errorf("URL is required for HTTP transport")
188 }
189 // Use streamable HTTP client for HTTP transport
190 var httpOptions []transport.StreamableHTTPCOption
191 if len(config.Headers) > 0 {
192 httpOptions = append(httpOptions, transport.WithHTTPHeaders(config.Headers))
193 }
194 mcpClient, err = client.NewStreamableHttpClient(config.URL, httpOptions...)
195 case "sse":
196 if config.URL == "" {
197 return nil, fmt.Errorf("URL is required for SSE transport")
198 }
199 var sseOptions []transport.ClientOption
200 if len(config.Headers) > 0 {
201 sseOptions = append(sseOptions, transport.WithHeaders(config.Headers))
202 }
203 mcpClient, err = client.NewSSEMCPClient(config.URL, sseOptions...)
204 default:
205 return nil, fmt.Errorf("unsupported MCP transport type: %s", config.Type)
206 }
207
208 if err != nil {
209 return nil, fmt.Errorf("failed to create MCP client: %w", err)
210 }
211
212 // Start the client first
213 if err := mcpClient.Start(ctx); err != nil {
214 return nil, fmt.Errorf("failed to start MCP client: %w", err)
215 }
216
217 // Initialize the client
218 initReq := mcp.InitializeRequest{
219 Params: mcp.InitializeParams{
220 ProtocolVersion: mcp.LATEST_PROTOCOL_VERSION,
221 Capabilities: mcp.ClientCapabilities{},
222 ClientInfo: mcp.Implementation{
223 Name: "sketch",
224 Version: "1.0.0",
225 },
226 },
227 }
228 if _, err := mcpClient.Initialize(ctx, initReq); err != nil {
229 return nil, fmt.Errorf("failed to initialize MCP client: %w", err)
230 }
231
232 // Get available tools
233 toolsReq := mcp.ListToolsRequest{}
234 toolsResp, err := mcpClient.ListTools(ctx, toolsReq)
235 if err != nil {
236 return nil, fmt.Errorf("failed to list tools: %w", err)
237 }
238
239 // Convert MCP tools to llm.Tool
240 llmTools, err := m.convertMCPTools(config.Name, mcpClient, toolsResp.Tools)
241 if err != nil {
242 return nil, fmt.Errorf("failed to convert tools: %w", err)
243 }
244
245 // Store the client
246 clientWrapper := &MCPClientWrapper{
247 name: config.Name,
248 config: config,
249 client: mcpClient,
250 tools: llmTools,
251 }
252
253 m.mu.Lock()
254 m.clients[config.Name] = clientWrapper
255 m.mu.Unlock()
256
257 return llmTools, nil
258}
259
260// convertMCPTools converts MCP tools to llm.Tool format
261func (m *MCPManager) convertMCPTools(serverName string, mcpClient *client.Client, mcpTools []mcp.Tool) ([]*llm.Tool, error) {
262 var llmTools []*llm.Tool
263
264 for _, mcpTool := range mcpTools {
265 // Convert the input schema
266 schemaBytes, err := json.Marshal(mcpTool.InputSchema)
267 if err != nil {
268 return nil, fmt.Errorf("failed to marshal input schema for tool %s: %w", mcpTool.Name, err)
269 }
270
271 llmTool := &llm.Tool{
272 Name: fmt.Sprintf("%s_%s", serverName, mcpTool.Name),
273 Description: mcpTool.Description,
274 InputSchema: json.RawMessage(schemaBytes),
275 Run: func(toolName string, client *client.Client) func(ctx context.Context, input json.RawMessage) ([]llm.Content, error) {
276 return func(ctx context.Context, input json.RawMessage) ([]llm.Content, error) {
277 result, err := m.executeMCPTool(ctx, client, toolName, input)
278 if err != nil {
279 return nil, err
280 }
281 // Convert result to llm.Content
282 return []llm.Content{llm.StringContent(fmt.Sprintf("%v", result))}, nil
283 }
284 }(mcpTool.Name, mcpClient),
285 }
286
287 llmTools = append(llmTools, llmTool)
288 }
289
290 return llmTools, nil
291}
292
293// executeMCPTool executes an MCP tool call
294func (m *MCPManager) executeMCPTool(ctx context.Context, mcpClient *client.Client, toolName string, input json.RawMessage) (any, error) {
295 // Add timeout for tool execution
296 ctxWithTimeout, cancel := context.WithTimeout(ctx, 30*time.Second)
297 defer cancel()
298
299 // Parse input arguments
300 var args map[string]any
301 if len(input) > 0 {
302 if err := json.Unmarshal(input, &args); err != nil {
303 return nil, fmt.Errorf("failed to parse tool arguments: %w", err)
304 }
305 }
306
307 // Call the MCP tool
308 req := mcp.CallToolRequest{
309 Params: mcp.CallToolParams{
310 Name: toolName,
311 Arguments: args,
312 },
313 }
314 resp, err := mcpClient.CallTool(ctxWithTimeout, req)
315 if err != nil {
316 return nil, fmt.Errorf("MCP tool call failed: %w", err)
317 }
318
319 // Return the content from the response
320 return resp.Content, nil
321}
322
323// Close closes all MCP client connections
324func (m *MCPManager) Close() {
325 m.mu.Lock()
326 defer m.mu.Unlock()
327
328 for _, clientWrapper := range m.clients {
329 if clientWrapper.client != nil {
330 clientWrapper.client.Close()
331 }
332 }
333 m.clients = make(map[string]*MCPClientWrapper)
334}