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