1// Package mcp provides functionality for managing Model Context Protocol (MCP)
2// clients within the Crush application.
3package mcp
4
5import (
6 "cmp"
7 "context"
8 "errors"
9 "fmt"
10 "io"
11 "log/slog"
12 "net/http"
13 "os"
14 "os/exec"
15 "strings"
16 "sync"
17 "time"
18
19 "github.com/charmbracelet/crush/internal/config"
20 "github.com/charmbracelet/crush/internal/csync"
21 "github.com/charmbracelet/crush/internal/home"
22 "github.com/charmbracelet/crush/internal/permission"
23 "github.com/charmbracelet/crush/internal/pubsub"
24 "github.com/charmbracelet/crush/internal/version"
25 "github.com/modelcontextprotocol/go-sdk/mcp"
26)
27
28var (
29 sessions = csync.NewMap[string, *mcp.ClientSession]()
30 states = csync.NewMap[string, ClientInfo]()
31 broker = pubsub.NewBroker[Event]()
32 initOnce sync.Once
33 initDone = make(chan struct{})
34)
35
36// State represents the current state of an MCP client
37type State int
38
39const (
40 StateDisabled State = iota
41 StateStarting
42 StateConnected
43 StateError
44)
45
46func (s State) String() string {
47 switch s {
48 case StateDisabled:
49 return "disabled"
50 case StateStarting:
51 return "starting"
52 case StateConnected:
53 return "connected"
54 case StateError:
55 return "error"
56 default:
57 return "unknown"
58 }
59}
60
61// EventType represents the type of MCP event
62type EventType uint
63
64const (
65 EventStateChanged EventType = iota
66 EventToolsListChanged
67 EventPromptsListChanged
68)
69
70// Event represents an event in the MCP system
71type Event struct {
72 Type EventType
73 Name string
74 State State
75 Error error
76 Counts Counts
77}
78
79// Counts number of available tools, prompts, etc.
80type Counts struct {
81 Tools int
82 Prompts int
83}
84
85// ClientInfo holds information about an MCP client's state
86type ClientInfo struct {
87 Name string
88 State State
89 Error error
90 Client *mcp.ClientSession
91 Counts Counts
92 ConnectedAt time.Time
93}
94
95// SubscribeEvents returns a channel for MCP events
96func SubscribeEvents(ctx context.Context) <-chan pubsub.Event[Event] {
97 return broker.Subscribe(ctx)
98}
99
100// GetStates returns the current state of all MCP clients
101func GetStates() map[string]ClientInfo {
102 return states.Copy()
103}
104
105// GetState returns the state of a specific MCP client
106func GetState(name string) (ClientInfo, bool) {
107 return states.Get(name)
108}
109
110// Close closes all MCP clients. This should be called during application shutdown.
111func Close() error {
112 var wg sync.WaitGroup
113 done := make(chan struct{}, 1)
114 go func() {
115 for name, session := range sessions.Seq2() {
116 wg.Go(func() {
117 if err := session.Close(); err != nil &&
118 !errors.Is(err, io.EOF) &&
119 !errors.Is(err, context.Canceled) &&
120 err.Error() != "signal: killed" {
121 slog.Warn("Failed to shutdown MCP client", "name", name, "error", err)
122 }
123 })
124 }
125 wg.Wait()
126 done <- struct{}{}
127 }()
128 select {
129 case <-done:
130 case <-time.After(5 * time.Second):
131 }
132 broker.Shutdown()
133 return nil
134}
135
136// Initialize initializes MCP clients based on the provided configuration.
137func Initialize(ctx context.Context, permissions permission.Service, cfg *config.Config) {
138 slog.Info("Initializing MCP clients")
139 var wg sync.WaitGroup
140 // Initialize states for all configured MCPs
141 for name, m := range cfg.MCP {
142 if m.Disabled {
143 updateState(name, StateDisabled, nil, nil, Counts{})
144 slog.Debug("Skipping disabled MCP", "name", name)
145 continue
146 }
147
148 // Set initial starting state
149 updateState(name, StateStarting, nil, nil, Counts{})
150
151 wg.Add(1)
152 go func(name string, m config.MCPConfig) {
153 defer func() {
154 wg.Done()
155 if r := recover(); r != nil {
156 var err error
157 switch v := r.(type) {
158 case error:
159 err = v
160 case string:
161 err = fmt.Errorf("panic: %s", v)
162 default:
163 err = fmt.Errorf("panic: %v", v)
164 }
165 updateState(name, StateError, err, nil, Counts{})
166 slog.Error("Panic in MCP client initialization", "error", err, "name", name)
167 }
168 }()
169
170 // createSession handles its own timeout internally.
171 session, err := createSession(ctx, name, m, cfg.Resolver())
172 if err != nil {
173 return
174 }
175
176 tools, err := getTools(ctx, session)
177 if err != nil {
178 slog.Error("Error listing tools", "error", err)
179 updateState(name, StateError, err, nil, Counts{})
180 session.Close()
181 return
182 }
183
184 prompts, err := getPrompts(ctx, session)
185 if err != nil {
186 slog.Error("Error listing prompts", "error", err)
187 updateState(name, StateError, err, nil, Counts{})
188 session.Close()
189 return
190 }
191
192 toolCount := updateTools(name, tools)
193 updatePrompts(name, prompts)
194 sessions.Set(name, session)
195
196 updateState(name, StateConnected, nil, session, Counts{
197 Tools: toolCount,
198 Prompts: len(prompts),
199 })
200 }(name, m)
201 }
202 wg.Wait()
203 initOnce.Do(func() { close(initDone) })
204}
205
206// WaitForInit blocks until MCP initialization is complete.
207// If Initialize was never called, this returns immediately.
208func WaitForInit(ctx context.Context) error {
209 select {
210 case <-initDone:
211 return nil
212 case <-ctx.Done():
213 return ctx.Err()
214 }
215}
216
217func getOrRenewClient(ctx context.Context, name string) (*mcp.ClientSession, error) {
218 sess, ok := sessions.Get(name)
219 if !ok {
220 return nil, fmt.Errorf("mcp '%s' not available", name)
221 }
222
223 cfg := config.Get()
224 m := cfg.MCP[name]
225 state, _ := states.Get(name)
226
227 timeout := mcpTimeout(m)
228 pingCtx, cancel := context.WithTimeout(ctx, timeout)
229 defer cancel()
230 err := sess.Ping(pingCtx, nil)
231 if err == nil {
232 return sess, nil
233 }
234 updateState(name, StateError, maybeTimeoutErr(err, timeout), nil, state.Counts)
235
236 sess, err = createSession(ctx, name, m, cfg.Resolver())
237 if err != nil {
238 return nil, err
239 }
240
241 updateState(name, StateConnected, nil, sess, state.Counts)
242 sessions.Set(name, sess)
243 return sess, nil
244}
245
246// updateState updates the state of an MCP client and publishes an event
247func updateState(name string, state State, err error, client *mcp.ClientSession, counts Counts) {
248 info := ClientInfo{
249 Name: name,
250 State: state,
251 Error: err,
252 Client: client,
253 Counts: counts,
254 }
255 switch state {
256 case StateConnected:
257 info.ConnectedAt = time.Now()
258 case StateError:
259 sessions.Del(name)
260 }
261 states.Set(name, info)
262
263 // Publish state change event
264 broker.Publish(pubsub.UpdatedEvent, Event{
265 Type: EventStateChanged,
266 Name: name,
267 State: state,
268 Error: err,
269 Counts: counts,
270 })
271}
272
273func createSession(ctx context.Context, name string, m config.MCPConfig, resolver config.VariableResolver) (*mcp.ClientSession, error) {
274 timeout := mcpTimeout(m)
275 mcpCtx, cancel := context.WithCancel(ctx)
276 cancelTimer := time.AfterFunc(timeout, cancel)
277
278 transport, err := createTransport(mcpCtx, m, resolver)
279 if err != nil {
280 updateState(name, StateError, err, nil, Counts{})
281 slog.Error("Error creating MCP client", "error", err, "name", name)
282 cancel()
283 cancelTimer.Stop()
284 return nil, err
285 }
286
287 client := mcp.NewClient(
288 &mcp.Implementation{
289 Name: "crush",
290 Version: version.Version,
291 Title: "Crush",
292 },
293 &mcp.ClientOptions{
294 ToolListChangedHandler: func(context.Context, *mcp.ToolListChangedRequest) {
295 broker.Publish(pubsub.UpdatedEvent, Event{
296 Type: EventToolsListChanged,
297 Name: name,
298 })
299 },
300 PromptListChangedHandler: func(context.Context, *mcp.PromptListChangedRequest) {
301 broker.Publish(pubsub.UpdatedEvent, Event{
302 Type: EventPromptsListChanged,
303 Name: name,
304 })
305 },
306 LoggingMessageHandler: func(_ context.Context, req *mcp.LoggingMessageRequest) {
307 slog.Info("MCP log", "name", name, "data", req.Params.Data)
308 },
309 },
310 )
311
312 session, err := client.Connect(mcpCtx, transport, nil)
313 if err != nil {
314 err = maybeStdioErr(err, transport)
315 updateState(name, StateError, maybeTimeoutErr(err, timeout), nil, Counts{})
316 slog.Error("MCP client failed to initialize", "error", err, "name", name)
317 cancel()
318 cancelTimer.Stop()
319 return nil, err
320 }
321
322 cancelTimer.Stop()
323 slog.Debug("MCP client initialized", "name", name)
324 return session, nil
325}
326
327// maybeStdioErr if a stdio mcp prints an error in non-json format, it'll fail
328// to parse, and the cli will then close it, causing the EOF error.
329// so, if we got an EOF err, and the transport is STDIO, we try to exec it
330// again with a timeout and collect the output so we can add details to the
331// error.
332// this happens particularly when starting things with npx, e.g. if node can't
333// be found or some other error like that.
334func maybeStdioErr(err error, transport mcp.Transport) error {
335 if !errors.Is(err, io.EOF) {
336 return err
337 }
338 ct, ok := transport.(*mcp.CommandTransport)
339 if !ok {
340 return err
341 }
342 if err2 := stdioCheck(ct.Command); err2 != nil {
343 err = errors.Join(err, err2)
344 }
345 return err
346}
347
348func maybeTimeoutErr(err error, timeout time.Duration) error {
349 if errors.Is(err, context.Canceled) {
350 return fmt.Errorf("timed out after %s", timeout)
351 }
352 return err
353}
354
355func createTransport(ctx context.Context, m config.MCPConfig, resolver config.VariableResolver) (mcp.Transport, error) {
356 switch m.Type {
357 case config.MCPStdio:
358 command, err := resolver.ResolveValue(m.Command)
359 if err != nil {
360 return nil, fmt.Errorf("invalid mcp command: %w", err)
361 }
362 if strings.TrimSpace(command) == "" {
363 return nil, fmt.Errorf("mcp stdio config requires a non-empty 'command' field")
364 }
365 cmd := exec.CommandContext(ctx, home.Long(command), m.Args...)
366 cmd.Env = append(os.Environ(), m.ResolvedEnv()...)
367 return &mcp.CommandTransport{
368 Command: cmd,
369 }, nil
370 case config.MCPHttp:
371 if strings.TrimSpace(m.URL) == "" {
372 return nil, fmt.Errorf("mcp http config requires a non-empty 'url' field")
373 }
374 client := &http.Client{
375 Transport: &headerRoundTripper{
376 headers: m.ResolvedHeaders(),
377 },
378 }
379 return &mcp.StreamableClientTransport{
380 Endpoint: m.URL,
381 HTTPClient: client,
382 }, nil
383 case config.MCPSSE:
384 if strings.TrimSpace(m.URL) == "" {
385 return nil, fmt.Errorf("mcp sse config requires a non-empty 'url' field")
386 }
387 client := &http.Client{
388 Transport: &headerRoundTripper{
389 headers: m.ResolvedHeaders(),
390 },
391 }
392 return &mcp.SSEClientTransport{
393 Endpoint: m.URL,
394 HTTPClient: client,
395 }, nil
396 default:
397 return nil, fmt.Errorf("unsupported mcp type: %s", m.Type)
398 }
399}
400
401type headerRoundTripper struct {
402 headers map[string]string
403}
404
405func (rt headerRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
406 for k, v := range rt.headers {
407 req.Header.Set(k, v)
408 }
409 return http.DefaultTransport.RoundTrip(req)
410}
411
412func mcpTimeout(m config.MCPConfig) time.Duration {
413 return time.Duration(cmp.Or(m.Timeout, 15)) * time.Second
414}
415
416func stdioCheck(old *exec.Cmd) error {
417 ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
418 defer cancel()
419 cmd := exec.CommandContext(ctx, old.Path, old.Args...)
420 cmd.Env = old.Env
421 out, err := cmd.CombinedOutput()
422 if err == nil || errors.Is(ctx.Err(), context.DeadlineExceeded) {
423 return nil
424 }
425 return fmt.Errorf("%w: %s", err, string(out))
426}