1// Package mcp provides functionality for managing Model Context Protocol (MCP)
2// clients within the Crush application.
20 "github.com/charmbracelet/crush/internal/config"
21 "github.com/charmbracelet/crush/internal/csync"
22 "github.com/charmbracelet/crush/internal/home"
23 "github.com/charmbracelet/crush/internal/permission"
24 "github.com/charmbracelet/crush/internal/pubsub"
25 "github.com/charmbracelet/crush/internal/version"
26 "github.com/modelcontextprotocol/go-sdk/mcp"
30 sessions = csync.NewMap[string, *mcp.ClientSession]()
31 states = csync.NewMap[string, ClientInfo]()
32 broker = pubsub.NewBroker[Event]()
35// State represents the current state of an MCP client
39 StateDisabled State = iota
45func (s State) String() string {
60// EventType represents the type of MCP event
64 EventStateChanged EventType = iota
66 EventPromptsListChanged
69// Event represents an event in the MCP system
78// Counts number of available tools, prompts, etc.
84// ClientInfo holds information about an MCP client's state
85type ClientInfo struct {
89 Client *mcp.ClientSession
94// SubscribeEvents returns a channel for MCP events
95func SubscribeEvents(ctx context.Context) <-chan pubsub.Event[Event] {
96 return broker.Subscribe(ctx)
99// GetStates returns the current state of all MCP clients
100func GetStates() map[string]ClientInfo {
101 return maps.Collect(states.Seq2())
104// GetState returns the state of a specific MCP client
105func GetState(name string) (ClientInfo, bool) {
106 return states.Get(name)
109// Close closes all MCP clients. This should be called during application shutdown.
112 var wg sync.WaitGroup
113 for name, session := range sessions.Seq2() {
115 done := make(chan bool, 1)
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 errs = append(errs, fmt.Errorf("close mcp: %s: %w", name, err))
127 case <-time.After(time.Millisecond * 250):
133 return errors.Join(errs...)
136// Initialize initializes MCP clients based on the provided configuration.
137func Initialize(ctx context.Context, permissions permission.Service, cfg *config.Config) {
138 var wg sync.WaitGroup
139 // Initialize states for all configured MCPs
140 for name, m := range cfg.MCP {
142 updateState(name, StateDisabled, nil, nil, Counts{})
143 slog.Debug("skipping disabled mcp", "name", name)
147 // Set initial starting state
148 updateState(name, StateStarting, nil, nil, Counts{})
151 go func(name string, m config.MCPConfig) {
154 if r := recover(); r != nil {
156 switch v := r.(type) {
160 err = fmt.Errorf("panic: %s", v)
162 err = fmt.Errorf("panic: %v", v)
164 updateState(name, StateError, err, nil, Counts{})
165 slog.Error("panic in mcp client initialization", "error", err, "name", name)
169 // createSession handles its own timeout internally.
170 session, err := createSession(ctx, name, m, cfg.Resolver())
175 tools, err := getTools(ctx, session)
177 slog.Error("error listing tools", "error", err)
178 updateState(name, StateError, err, nil, Counts{})
183 prompts, err := getPrompts(ctx, session)
185 slog.Error("error listing prompts", "error", err)
186 updateState(name, StateError, err, nil, Counts{})
191 updateTools(name, tools)
192 updatePrompts(name, prompts)
193 sessions.Set(name, session)
195 updateState(name, StateConnected, nil, session, Counts{
197 Prompts: len(prompts),
204func getOrRenewClient(ctx context.Context, name string) (*mcp.ClientSession, error) {
205 sess, ok := sessions.Get(name)
207 return nil, fmt.Errorf("mcp '%s' not available", name)
212 state, _ := states.Get(name)
214 timeout := mcpTimeout(m)
215 pingCtx, cancel := context.WithTimeout(ctx, timeout)
217 err := sess.Ping(pingCtx, nil)
221 updateState(name, StateError, maybeTimeoutErr(err, timeout), nil, state.Counts)
223 sess, err = createSession(ctx, name, m, cfg.Resolver())
228 updateState(name, StateConnected, nil, sess, state.Counts)
229 sessions.Set(name, sess)
233// updateState updates the state of an MCP client and publishes an event
234func updateState(name string, state State, err error, client *mcp.ClientSession, counts Counts) {
244 info.ConnectedAt = time.Now()
248 states.Set(name, info)
250 // Publish state change event
251 broker.Publish(pubsub.UpdatedEvent, Event{
252 Type: EventStateChanged,
260func createSession(ctx context.Context, name string, m config.MCPConfig, resolver config.VariableResolver) (*mcp.ClientSession, error) {
261 timeout := mcpTimeout(m)
262 mcpCtx, cancel := context.WithCancel(ctx)
263 cancelTimer := time.AfterFunc(timeout, cancel)
265 transport, err := createTransport(mcpCtx, m, resolver)
267 updateState(name, StateError, err, nil, Counts{})
268 slog.Error("error creating mcp client", "error", err, "name", name)
274 client := mcp.NewClient(
277 Version: version.Version,
281 ToolListChangedHandler: func(context.Context, *mcp.ToolListChangedRequest) {
282 broker.Publish(pubsub.UpdatedEvent, Event{
283 Type: EventToolsListChanged,
287 PromptListChangedHandler: func(context.Context, *mcp.PromptListChangedRequest) {
288 broker.Publish(pubsub.UpdatedEvent, Event{
289 Type: EventPromptsListChanged,
293 LoggingMessageHandler: func(_ context.Context, req *mcp.LoggingMessageRequest) {
294 slog.Info("MCP log", "name", name, "data", req.Params.Data)
299 session, err := client.Connect(mcpCtx, transport, nil)
301 err = maybeStdioErr(err, transport)
302 updateState(name, StateError, maybeTimeoutErr(err, timeout), nil, Counts{})
303 slog.Error("MCP client failed to initialize", "error", err, "name", name)
310 slog.Info("MCP client initialized", "name", name)
314// maybeStdioErr if a stdio mcp prints an error in non-json format, it'll fail
315// to parse, and the cli will then close it, causing the EOF error.
316// so, if we got an EOF err, and the transport is STDIO, we try to exec it
317// again with a timeout and collect the output so we can add details to the
319// this happens particularly when starting things with npx, e.g. if node can't
320// be found or some other error like that.
321func maybeStdioErr(err error, transport mcp.Transport) error {
322 if !errors.Is(err, io.EOF) {
325 ct, ok := transport.(*mcp.CommandTransport)
329 if err2 := stdioCheck(ct.Command); err2 != nil {
330 err = errors.Join(err, err2)
335func maybeTimeoutErr(err error, timeout time.Duration) error {
336 if errors.Is(err, context.Canceled) {
337 return fmt.Errorf("timed out after %s", timeout)
342func createTransport(ctx context.Context, m config.MCPConfig, resolver config.VariableResolver) (mcp.Transport, error) {
344 case config.MCPStdio:
345 command, err := resolver.ResolveValue(m.Command)
347 return nil, fmt.Errorf("invalid mcp command: %w", err)
349 if strings.TrimSpace(command) == "" {
350 return nil, fmt.Errorf("mcp stdio config requires a non-empty 'command' field")
352 cmd := exec.CommandContext(ctx, home.Long(command), m.Args...)
353 cmd.Env = append(os.Environ(), m.ResolvedEnv()...)
354 return &mcp.CommandTransport{
358 if strings.TrimSpace(m.URL) == "" {
359 return nil, fmt.Errorf("mcp http config requires a non-empty 'url' field")
361 client := &http.Client{
362 Transport: &headerRoundTripper{
363 headers: m.ResolvedHeaders(),
366 return &mcp.StreamableClientTransport{
371 if strings.TrimSpace(m.URL) == "" {
372 return nil, fmt.Errorf("mcp sse config requires a non-empty 'url' field")
374 client := &http.Client{
375 Transport: &headerRoundTripper{
376 headers: m.ResolvedHeaders(),
379 return &mcp.SSEClientTransport{
384 return nil, fmt.Errorf("unsupported mcp type: %s", m.Type)
388type headerRoundTripper struct {
389 headers map[string]string
392func (rt headerRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
393 for k, v := range rt.headers {
396 return http.DefaultTransport.RoundTrip(req)
399func mcpTimeout(m config.MCPConfig) time.Duration {
400 return time.Duration(cmp.Or(m.Timeout, 15)) * time.Second
403func stdioCheck(old *exec.Cmd) error {
404 ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
406 cmd := exec.CommandContext(ctx, old.Path, old.Args...)
408 out, err := cmd.CombinedOutput()
409 if err == nil || errors.Is(ctx.Err(), context.DeadlineExceeded) {
412 return fmt.Errorf("%w: %s", err, string(out))
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list