mcp-tools.go

  1package agent
  2
  3import (
  4	"cmp"
  5	"context"
  6	"encoding/json"
  7	"errors"
  8	"fmt"
  9	"log/slog"
 10	"maps"
 11	"strings"
 12	"sync"
 13	"time"
 14
 15	"github.com/charmbracelet/crush/internal/config"
 16	"github.com/charmbracelet/crush/internal/csync"
 17	"github.com/charmbracelet/crush/internal/home"
 18	"github.com/charmbracelet/crush/internal/llm/tools"
 19	"github.com/charmbracelet/crush/internal/permission"
 20	"github.com/charmbracelet/crush/internal/pubsub"
 21	"github.com/charmbracelet/crush/internal/version"
 22	"github.com/mark3labs/mcp-go/client"
 23	"github.com/mark3labs/mcp-go/client/transport"
 24	"github.com/mark3labs/mcp-go/mcp"
 25)
 26
 27// MCPState represents the current state of an MCP client
 28type MCPState int
 29
 30const (
 31	MCPStateDisabled MCPState = iota
 32	MCPStateStarting
 33	MCPStateConnected
 34	MCPStateError
 35)
 36
 37func (s MCPState) String() string {
 38	switch s {
 39	case MCPStateDisabled:
 40		return "disabled"
 41	case MCPStateStarting:
 42		return "starting"
 43	case MCPStateConnected:
 44		return "connected"
 45	case MCPStateError:
 46		return "error"
 47	default:
 48		return "unknown"
 49	}
 50}
 51
 52// MCPEventType represents the type of MCP event
 53type MCPEventType string
 54
 55const (
 56	MCPEventStateChanged     MCPEventType = "state_changed"
 57	MCPEventToolsListChanged MCPEventType = "tools_list_changed"
 58)
 59
 60// MCPEvent represents an event in the MCP system
 61type MCPEvent struct {
 62	Type      MCPEventType
 63	Name      string
 64	State     MCPState
 65	Error     error
 66	ToolCount int
 67}
 68
 69// MCPClientInfo holds information about an MCP client's state
 70type MCPClientInfo struct {
 71	Name        string
 72	State       MCPState
 73	Error       error
 74	Client      *client.Client
 75	ToolCount   int
 76	ConnectedAt time.Time
 77}
 78
 79var (
 80	mcpToolsOnce    sync.Once
 81	mcpTools        = csync.NewMap[string, tools.BaseTool]()
 82	mcpClient2Tools = csync.NewMap[string, []tools.BaseTool]()
 83	mcpClients      = csync.NewMap[string, *client.Client]()
 84	mcpStates       = csync.NewMap[string, MCPClientInfo]()
 85	mcpBroker       = pubsub.NewBroker[MCPEvent]()
 86)
 87
 88type McpTool struct {
 89	mcpName     string
 90	tool        mcp.Tool
 91	permissions permission.Service
 92	workingDir  string
 93}
 94
 95func (b *McpTool) Name() string {
 96	return fmt.Sprintf("mcp_%s_%s", b.mcpName, b.tool.Name)
 97}
 98
 99func (b *McpTool) Info() tools.ToolInfo {
100	required := b.tool.InputSchema.Required
101	if required == nil {
102		required = make([]string, 0)
103	}
104	parameters := b.tool.InputSchema.Properties
105	if parameters == nil {
106		parameters = make(map[string]any)
107	}
108	return tools.ToolInfo{
109		Name:        fmt.Sprintf("mcp_%s_%s", b.mcpName, b.tool.Name),
110		Description: b.tool.Description,
111		Parameters:  parameters,
112		Required:    required,
113	}
114}
115
116func runTool(ctx context.Context, name, toolName string, input string) (tools.ToolResponse, error) {
117	var args map[string]any
118	if err := json.Unmarshal([]byte(input), &args); err != nil {
119		return tools.NewTextErrorResponse(fmt.Sprintf("error parsing parameters: %s", err)), nil
120	}
121
122	c, err := getOrRenewClient(ctx, name)
123	if err != nil {
124		return tools.NewTextErrorResponse(err.Error()), nil
125	}
126	result, err := c.CallTool(ctx, mcp.CallToolRequest{
127		Params: mcp.CallToolParams{
128			Name:      toolName,
129			Arguments: args,
130		},
131	})
132	if err != nil {
133		return tools.NewTextErrorResponse(err.Error()), nil
134	}
135
136	output := make([]string, 0, len(result.Content))
137	for _, v := range result.Content {
138		if v, ok := v.(mcp.TextContent); ok {
139			output = append(output, v.Text)
140		} else {
141			output = append(output, fmt.Sprintf("%v", v))
142		}
143	}
144	return tools.NewTextResponse(strings.Join(output, "\n")), nil
145}
146
147func getOrRenewClient(ctx context.Context, name string) (*client.Client, error) {
148	c, ok := mcpClients.Get(name)
149	if !ok {
150		return nil, fmt.Errorf("mcp '%s' not available", name)
151	}
152
153	cfg := config.Get()
154	m := cfg.MCP[name]
155	state, _ := mcpStates.Get(name)
156
157	timeout := mcpTimeout(m)
158	pingCtx, cancel := context.WithTimeout(ctx, timeout)
159	defer cancel()
160	err := c.Ping(pingCtx)
161	if err == nil {
162		return c, nil
163	}
164	updateMCPState(name, MCPStateError, maybeTimeoutErr(err, timeout), nil, state.ToolCount)
165
166	c, err = createAndInitializeClient(ctx, name, m, cfg.Resolver())
167	if err != nil {
168		return nil, err
169	}
170
171	updateMCPState(name, MCPStateConnected, nil, c, state.ToolCount)
172	mcpClients.Set(name, c)
173	return c, nil
174}
175
176func (b *McpTool) Run(ctx context.Context, params tools.ToolCall) (tools.ToolResponse, error) {
177	sessionID, messageID := tools.GetContextValues(ctx)
178	if sessionID == "" || messageID == "" {
179		return tools.ToolResponse{}, fmt.Errorf("session ID and message ID are required for creating a new file")
180	}
181	permissionDescription := fmt.Sprintf("execute %s with the following parameters:", b.Info().Name)
182	p := b.permissions.Request(
183		permission.CreatePermissionRequest{
184			SessionID:   sessionID,
185			ToolCallID:  params.ID,
186			Path:        b.workingDir,
187			ToolName:    b.Info().Name,
188			Action:      "execute",
189			Description: permissionDescription,
190			Params:      params.Input,
191		},
192	)
193	if !p {
194		return tools.ToolResponse{}, permission.ErrorPermissionDenied
195	}
196
197	return runTool(ctx, b.mcpName, b.tool.Name, params.Input)
198}
199
200func getTools(ctx context.Context, name string, permissions permission.Service, c *client.Client, workingDir string) []tools.BaseTool {
201	result, err := c.ListTools(ctx, mcp.ListToolsRequest{})
202	if err != nil {
203		slog.Error("error listing tools", "error", err)
204		updateMCPState(name, MCPStateError, err, nil, 0)
205		c.Close()
206		return nil
207	}
208	mcpTools := make([]tools.BaseTool, 0, len(result.Tools))
209	for _, tool := range result.Tools {
210		mcpTools = append(mcpTools, &McpTool{
211			mcpName:     name,
212			tool:        tool,
213			permissions: permissions,
214			workingDir:  workingDir,
215		})
216	}
217	return mcpTools
218}
219
220// SubscribeMCPEvents returns a channel for MCP events
221func SubscribeMCPEvents(ctx context.Context) <-chan pubsub.Event[MCPEvent] {
222	return mcpBroker.Subscribe(ctx)
223}
224
225// GetMCPStates returns the current state of all MCP clients
226func GetMCPStates() map[string]MCPClientInfo {
227	return maps.Collect(mcpStates.Seq2())
228}
229
230// GetMCPState returns the state of a specific MCP client
231func GetMCPState(name string) (MCPClientInfo, bool) {
232	return mcpStates.Get(name)
233}
234
235// updateMCPState updates the state of an MCP client and publishes an event
236func updateMCPState(name string, state MCPState, err error, client *client.Client, toolCount int) {
237	info := MCPClientInfo{
238		Name:      name,
239		State:     state,
240		Error:     err,
241		Client:    client,
242		ToolCount: toolCount,
243	}
244	switch state {
245	case MCPStateConnected:
246		info.ConnectedAt = time.Now()
247	case MCPStateError:
248		updateMcpTools(name, nil)
249		mcpClients.Del(name)
250	}
251	mcpStates.Set(name, info)
252
253	// Publish state change event
254	mcpBroker.Publish(pubsub.UpdatedEvent, MCPEvent{
255		Type:      MCPEventStateChanged,
256		Name:      name,
257		State:     state,
258		Error:     err,
259		ToolCount: toolCount,
260	})
261}
262
263// publishMCPEventToolsListChanged publishes a tool list changed event
264func publishMCPEventToolsListChanged(name string) {
265	mcpBroker.Publish(pubsub.UpdatedEvent, MCPEvent{
266		Type: MCPEventToolsListChanged,
267		Name: name,
268	})
269}
270
271// CloseMCPClients closes all MCP clients. This should be called during application shutdown.
272func CloseMCPClients() error {
273	var errs []error
274	for name, c := range mcpClients.Seq2() {
275		if err := c.Close(); err != nil {
276			errs = append(errs, fmt.Errorf("close mcp: %s: %w", name, err))
277		}
278	}
279	mcpBroker.Shutdown()
280	return errors.Join(errs...)
281}
282
283var mcpInitRequest = mcp.InitializeRequest{
284	Params: mcp.InitializeParams{
285		ProtocolVersion: mcp.LATEST_PROTOCOL_VERSION,
286		ClientInfo: mcp.Implementation{
287			Name:    "Crush",
288			Version: version.Version,
289		},
290	},
291}
292
293func doGetMCPTools(ctx context.Context, permissions permission.Service, cfg *config.Config) {
294	var wg sync.WaitGroup
295	// Initialize states for all configured MCPs
296	for name, m := range cfg.MCP {
297		if m.Disabled {
298			updateMCPState(name, MCPStateDisabled, nil, nil, 0)
299			slog.Debug("skipping disabled mcp", "name", name)
300			continue
301		}
302
303		// Set initial starting state
304		updateMCPState(name, MCPStateStarting, nil, nil, 0)
305
306		wg.Add(1)
307		go func(name string, m config.MCPConfig) {
308			defer func() {
309				wg.Done()
310				if r := recover(); r != nil {
311					var err error
312					switch v := r.(type) {
313					case error:
314						err = v
315					case string:
316						err = fmt.Errorf("panic: %s", v)
317					default:
318						err = fmt.Errorf("panic: %v", v)
319					}
320					updateMCPState(name, MCPStateError, err, nil, 0)
321					slog.Error("panic in mcp client initialization", "error", err, "name", name)
322				}
323			}()
324
325			ctx, cancel := context.WithTimeout(ctx, mcpTimeout(m))
326			defer cancel()
327			c, err := createAndInitializeClient(ctx, name, m, cfg.Resolver())
328			if err != nil {
329				return
330			}
331
332			mcpClients.Set(name, c)
333
334			tools := getTools(ctx, name, permissions, c, cfg.WorkingDir())
335			updateMcpTools(name, tools)
336			updateMCPState(name, MCPStateConnected, nil, c, len(tools))
337		}(name, m)
338	}
339	wg.Wait()
340}
341
342// updateMcpTools updates the global mcpTools and mcpClient2Tools maps
343func updateMcpTools(mcpName string, tools []tools.BaseTool) {
344	if len(tools) == 0 {
345		mcpClient2Tools.Del(mcpName)
346	} else {
347		mcpClient2Tools.Set(mcpName, tools)
348	}
349	for _, tools := range mcpClient2Tools.Seq2() {
350		for _, t := range tools {
351			mcpTools.Set(t.Name(), t)
352		}
353	}
354}
355
356func createAndInitializeClient(ctx context.Context, name string, m config.MCPConfig, resolver config.VariableResolver) (*client.Client, error) {
357	c, err := createMcpClient(name, m, resolver)
358	if err != nil {
359		updateMCPState(name, MCPStateError, err, nil, 0)
360		slog.Error("error creating mcp client", "error", err, "name", name)
361		return nil, err
362	}
363
364	c.OnNotification(func(n mcp.JSONRPCNotification) {
365		slog.Debug("Received MCP notification", "name", name, "notification", n)
366		switch n.Method {
367		case "notifications/tools/list_changed":
368			publishMCPEventToolsListChanged(name)
369		default:
370			slog.Debug("Unhandled MCP notification", "name", name, "method", n.Method)
371		}
372	})
373
374	timeout := mcpTimeout(m)
375	initCtx, cancel := context.WithTimeout(ctx, timeout)
376	defer cancel()
377
378	if err := c.Start(ctx); err != nil {
379		updateMCPState(name, MCPStateError, err, nil, 0)
380		slog.Error("error starting mcp client", "error", err, "name", name)
381		_ = c.Close()
382		return nil, err
383	}
384
385	if _, err := c.Initialize(initCtx, mcpInitRequest); err != nil {
386		updateMCPState(name, MCPStateError, maybeTimeoutErr(err, timeout), nil, 0)
387		slog.Error("error initializing mcp client", "error", err, "name", name)
388		_ = c.Close()
389		return nil, err
390	}
391
392	slog.Info("Initialized mcp client", "name", name)
393	return c, nil
394}
395
396func maybeTimeoutErr(err error, timeout time.Duration) error {
397	if errors.Is(err, context.DeadlineExceeded) {
398		return fmt.Errorf("timed out after %s", timeout)
399	}
400	return err
401}
402
403func createMcpClient(name string, m config.MCPConfig, resolver config.VariableResolver) (*client.Client, error) {
404	switch m.Type {
405	case config.MCPStdio:
406		command, err := resolver.ResolveValue(m.Command)
407		if err != nil {
408			return nil, fmt.Errorf("invalid mcp command: %w", err)
409		}
410		if strings.TrimSpace(command) == "" {
411			return nil, fmt.Errorf("mcp stdio config requires a non-empty 'command' field")
412		}
413		return client.NewStdioMCPClientWithOptions(
414			home.Long(command),
415			m.ResolvedEnv(),
416			m.Args,
417			transport.WithCommandLogger(mcpLogger{name: name}),
418		)
419	case config.MCPHttp:
420		if strings.TrimSpace(m.URL) == "" {
421			return nil, fmt.Errorf("mcp http config requires a non-empty 'url' field")
422		}
423		return client.NewStreamableHttpClient(
424			m.URL,
425			transport.WithHTTPHeaders(m.ResolvedHeaders()),
426			transport.WithHTTPLogger(mcpLogger{name: name}),
427		)
428	case config.MCPSse:
429		if strings.TrimSpace(m.URL) == "" {
430			return nil, fmt.Errorf("mcp sse config requires a non-empty 'url' field")
431		}
432		return client.NewSSEMCPClient(
433			m.URL,
434			client.WithHeaders(m.ResolvedHeaders()),
435			transport.WithSSELogger(mcpLogger{name: name}),
436		)
437	default:
438		return nil, fmt.Errorf("unsupported mcp type: %s", m.Type)
439	}
440}
441
442// for MCP's clients.
443type mcpLogger struct{ name string }
444
445func (l mcpLogger) Errorf(format string, v ...any) {
446	slog.Error(fmt.Sprintf(format, v...), "name", l.name)
447}
448
449func (l mcpLogger) Infof(format string, v ...any) {
450	slog.Info(fmt.Sprintf(format, v...), "name", l.name)
451}
452
453func mcpTimeout(m config.MCPConfig) time.Duration {
454	return time.Duration(cmp.Or(m.Timeout, 15)) * time.Second
455}