blob: 1ebcd1972f5f043a9611c34e001facf034f16563 [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...)
Philip Zeyliger08b073b2025-07-18 10:40:00 -0700185 // TODO: Get the transport, cast it to *transport.Stdio, and start a goroutine to pipe stderr from the subprocess
186 // to our subprocess, but with each line prefixed with the server name.
Philip Zeyliger194bfa82025-06-24 06:03:06 -0700187 case "http":
188 if config.URL == "" {
189 return nil, fmt.Errorf("URL is required for HTTP transport")
190 }
191 // Use streamable HTTP client for HTTP transport
192 var httpOptions []transport.StreamableHTTPCOption
193 if len(config.Headers) > 0 {
194 httpOptions = append(httpOptions, transport.WithHTTPHeaders(config.Headers))
195 }
196 mcpClient, err = client.NewStreamableHttpClient(config.URL, httpOptions...)
197 case "sse":
198 if config.URL == "" {
199 return nil, fmt.Errorf("URL is required for SSE transport")
200 }
201 var sseOptions []transport.ClientOption
202 if len(config.Headers) > 0 {
203 sseOptions = append(sseOptions, transport.WithHeaders(config.Headers))
204 }
205 mcpClient, err = client.NewSSEMCPClient(config.URL, sseOptions...)
206 default:
207 return nil, fmt.Errorf("unsupported MCP transport type: %s", config.Type)
208 }
209
210 if err != nil {
211 return nil, fmt.Errorf("failed to create MCP client: %w", err)
212 }
213
214 // Start the client first
215 if err := mcpClient.Start(ctx); err != nil {
216 return nil, fmt.Errorf("failed to start MCP client: %w", err)
217 }
218
219 // Initialize the client
220 initReq := mcp.InitializeRequest{
221 Params: mcp.InitializeParams{
222 ProtocolVersion: mcp.LATEST_PROTOCOL_VERSION,
223 Capabilities: mcp.ClientCapabilities{},
224 ClientInfo: mcp.Implementation{
225 Name: "sketch",
226 Version: "1.0.0",
227 },
228 },
229 }
230 if _, err := mcpClient.Initialize(ctx, initReq); err != nil {
231 return nil, fmt.Errorf("failed to initialize MCP client: %w", err)
232 }
233
234 // Get available tools
235 toolsReq := mcp.ListToolsRequest{}
236 toolsResp, err := mcpClient.ListTools(ctx, toolsReq)
237 if err != nil {
238 return nil, fmt.Errorf("failed to list tools: %w", err)
239 }
240
241 // Convert MCP tools to llm.Tool
242 llmTools, err := m.convertMCPTools(config.Name, mcpClient, toolsResp.Tools)
243 if err != nil {
244 return nil, fmt.Errorf("failed to convert tools: %w", err)
245 }
246
247 // Store the client
248 clientWrapper := &MCPClientWrapper{
249 name: config.Name,
250 config: config,
251 client: mcpClient,
252 tools: llmTools,
253 }
254
255 m.mu.Lock()
256 m.clients[config.Name] = clientWrapper
257 m.mu.Unlock()
258
259 return llmTools, nil
260}
261
262// convertMCPTools converts MCP tools to llm.Tool format
263func (m *MCPManager) convertMCPTools(serverName string, mcpClient *client.Client, mcpTools []mcp.Tool) ([]*llm.Tool, error) {
264 var llmTools []*llm.Tool
265
266 for _, mcpTool := range mcpTools {
267 // Convert the input schema
268 schemaBytes, err := json.Marshal(mcpTool.InputSchema)
269 if err != nil {
270 return nil, fmt.Errorf("failed to marshal input schema for tool %s: %w", mcpTool.Name, err)
271 }
272
273 llmTool := &llm.Tool{
274 Name: fmt.Sprintf("%s_%s", serverName, mcpTool.Name),
275 Description: mcpTool.Description,
276 InputSchema: json.RawMessage(schemaBytes),
277 Run: func(toolName string, client *client.Client) func(ctx context.Context, input json.RawMessage) ([]llm.Content, error) {
278 return func(ctx context.Context, input json.RawMessage) ([]llm.Content, error) {
279 result, err := m.executeMCPTool(ctx, client, toolName, input)
280 if err != nil {
281 return nil, err
282 }
283 // Convert result to llm.Content
284 return []llm.Content{llm.StringContent(fmt.Sprintf("%v", result))}, nil
285 }
286 }(mcpTool.Name, mcpClient),
287 }
288
289 llmTools = append(llmTools, llmTool)
290 }
291
292 return llmTools, nil
293}
294
295// executeMCPTool executes an MCP tool call
296func (m *MCPManager) executeMCPTool(ctx context.Context, mcpClient *client.Client, toolName string, input json.RawMessage) (any, error) {
297 // Add timeout for tool execution
Philip Zeyliger08b073b2025-07-18 10:40:00 -0700298 // TODO: Expose the timeout as a tool call argument.
299 ctxWithTimeout, cancel := context.WithTimeout(ctx, 120*time.Second)
Philip Zeyliger194bfa82025-06-24 06:03:06 -0700300 defer cancel()
301
302 // Parse input arguments
303 var args map[string]any
304 if len(input) > 0 {
305 if err := json.Unmarshal(input, &args); err != nil {
306 return nil, fmt.Errorf("failed to parse tool arguments: %w", err)
307 }
308 }
309
310 // Call the MCP tool
311 req := mcp.CallToolRequest{
312 Params: mcp.CallToolParams{
313 Name: toolName,
314 Arguments: args,
315 },
316 }
317 resp, err := mcpClient.CallTool(ctxWithTimeout, req)
318 if err != nil {
319 return nil, fmt.Errorf("MCP tool call failed: %w", err)
320 }
321
322 // Return the content from the response
323 return resp.Content, nil
324}
325
326// Close closes all MCP client connections
327func (m *MCPManager) Close() {
328 m.mu.Lock()
329 defer m.mu.Unlock()
330
331 for _, clientWrapper := range m.clients {
332 if clientWrapper.client != nil {
333 clientWrapper.client.Close()
334 }
335 }
336 m.clients = make(map[string]*MCPClientWrapper)
337}