Files
skillshare/internal/server/handler_mcp.go
T
Willie 7ee08b913d feat(mcp): open an Agent's MCP config file from the dashboard (#552)
* feat(mcp): open an Agent's MCP config file from the dashboard

Users asked to jump from the MCP page straight into a client's config
file, such as opencode.json or .cursor/mcp.json, instead of copying the
path and opening it by hand (#538).

The open uses the same editor chain as a skill's Open in editor, so the
dashboard opens files one way. The endpoint takes a target, not a path,
and only opens a file the MCP page already lists. It answers only
requests from the machine running the dashboard, because the editor
starts on that machine. The list now reports which files exist, so the
button is hidden for a client detected before it has a file.

* fix(mcp): hide Open in editor where the server would refuse it

Codex review: the dashboard can be opened through a LAN IP, but the
open endpoint answers only loopback requests, so the button showed and
every click returned 403, while the docs promised it would open.

The list now reports `openable` instead of `existing`: the files that
exist, and only when the request comes from the dashboard's machine. A
viewer elsewhere does not see the button, and the docs say where it
appears.

* fix(mcp): don't treat a reverse proxy's viewers as local for Open in editor

Codex review: the documented Nginx and Caddy setups connect from
127.0.0.1, so the loopback socket check let any browser behind the proxy
see the button and launch editors on the server.

The browser now counts as local only when the socket and the Host it
used are both loopback and no proxy forwarding header is present. Both
documented proxies keep the browser's Host and add X-Real-IP or
X-Forwarded-For, so their viewers no longer qualify.
2026-10-13 10:40:27 +08:00

349 lines
10 KiB
Go

package server
import (
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"os"
"reflect"
"slices"
"strings"
"time"
"skillshare/internal/config"
"skillshare/internal/mcp"
"skillshare/internal/projectdir"
syncpkg "skillshare/internal/sync"
)
func (s *Server) mcpService() *mcp.Service {
return &mcp.Service{ConfigPath: s.configPath(), ProjectRoot: s.projectRoot, StateDir: config.StateDir(), ConfigDirs: mcp.ConfigDirsFromEnv(), BackupSource: func(path string) (string, error) {
return syncpkg.StoreBackup(path, syncpkg.BackupReasonMigrate)
}}
}
type mcpRequest struct {
Mutation mcp.Mutation `json:"mutation"`
Revision string `json:"revision"`
Sync bool `json:"sync"`
BackupID string `json:"backupId"`
Preview bool `json:"preview"`
// Root, with sync and no mutation, applies only that mcp.projects root's changes.
Root string `json:"root"`
}
func decodeMCPRequest(w http.ResponseWriter, r *http.Request, value any) bool {
var extra bool
err := decodeJSONWith(w, r, defaultJSONBodyLimit, func(d *json.Decoder) error {
d.DisallowUnknownFields()
if err := d.Decode(value); err != nil {
return err
}
extra = d.Decode(new(any)) != io.EOF
return nil
})
switch {
case errors.Is(err, errBodyTooLarge):
return false
case err != nil:
writeError(w, 400, "invalid MCP request")
return false
case extra:
writeError(w, 400, "expected one MCP request")
return false
}
return true
}
func (s *Server) handleMCPList(w http.ResponseWriter, r *http.Request) {
s.mu.RLock()
defer s.mu.RUnlock()
service := s.mcpService()
source, err := mcp.LoadSource(service.ConfigPath)
if err != nil {
writeError(w, 400, err.Error())
return
}
// Unresolvable paths are omitted; selected targets report them via previewError.
paths := service.ConfiguredClientPaths(source)
p, previewErr := service.Preview()
message := ""
if previewErr != nil {
message = previewErr.Error()
}
backups, err := service.Backups()
if err != nil {
writeError(w, 500, err.Error())
return
}
// A root with its own project config is managed from two places; the plan reports a
// conflict when both hold one entry, so the dashboard says so up front.
ownConfig := []string{}
for root := range source.Projects {
if _, ok := projectdir.Find(root); ok {
ownConfig = append(ownConfig, root)
}
}
slices.Sort(ownConfig)
detected := service.DetectedClients(paths)
// A client can be detected before its file exists, and handleMCPOpen refuses a viewer on
// another machine, so list only the files this viewer can open.
openable := []string{}
for target, path := range paths {
if _, err := os.Stat(path); err == nil && browserOnServerMachine(r) {
openable = append(openable, target)
}
}
slices.Sort(openable)
if !s.IsProjectMode() {
detected = append(detected, mcp.DetectedAccounts(source.Accounts)...)
}
writeJSON(w, map[string]any{"source": source, "paths": paths, "importSources": service.ImportSources(source), "detected": detected, "openable": openable, "plan": p, "previewError": message, "backups": backups, "projectConfigs": ownConfig, "unmanaged": service.FindUnmanaged(source)})
}
func (s *Server) handleMCPPreview(w http.ResponseWriter, r *http.Request) {
var body mcpRequest
if !decodeMCPRequest(w, r, &body) {
return
}
s.mu.RLock()
defer s.mu.RUnlock()
p, err := s.mcpService().PreviewMutation(body.Mutation)
if err != nil {
writeError(w, 400, err.Error())
return
}
writeJSON(w, p)
}
// handleMCPRender shows the server in the request as each of its targets would store it.
// It reads configuration only; it neither executes servers nor writes files.
func (s *Server) handleMCPRender(w http.ResponseWriter, r *http.Request) {
var body mcpRequest
if !decodeMCPRequest(w, r, &body) {
return
}
if body.Mutation.Server == nil {
writeError(w, 400, "server is required")
return
}
service, ok := s.mcpProjectService(w, body.Mutation.Project)
if !ok {
return
}
writeJSON(w, map[string]any{"rendered": service.RenderNative(body.Mutation.Name, *body.Mutation.Server)})
}
// mcpProjectService is the service for one mcp.projects root, or for this scope when
// project is empty. It writes the error and reports false when the root is not configured.
func (s *Server) mcpProjectService(w http.ResponseWriter, project string) (*mcp.Service, bool) {
service := s.mcpService()
if project == "" {
return service, true
}
if service.ProjectRoot != "" {
writeError(w, 400, "MCP project overrides are not available in project mode; omit mutation.project")
return nil, false
}
source, err := mcp.LoadSource(service.ConfigPath)
if err != nil {
writeError(w, 400, err.Error())
return nil, false
}
if _, ok := source.Projects[project]; !ok {
writeError(w, 400, "unknown MCP project")
return nil, false
}
service.ProjectRoot = project
return service, true
}
func (s *Server) handleMCPConfigure(w http.ResponseWriter, r *http.Request) {
var body mcpRequest
if !decodeMCPRequest(w, r, &body) {
return
}
if body.Revision == "" {
writeError(w, 400, "preview the MCP changes before saving")
return
}
if body.Root != "" && (!body.Sync || !reflect.DeepEqual(body.Mutation, mcp.Mutation{})) {
writeError(w, 400, "a project sync takes no changes")
return
}
s.mu.Lock()
defer s.mu.Unlock()
start := time.Now()
var result *mcp.Result
var err error
logArgs := map[string]any{"scope": "ui"}
if body.Root != "" {
logArgs["project"] = body.Root
result, err = s.mcpService().ApplyProject(body.Revision, body.Root)
} else {
result, err = s.mcpService().Mutate(body.Mutation, body.Revision, body.Sync)
}
status := "ok"
if err != nil {
status = "error"
}
s.writeOpsLog("mcp configure", status, start, logArgs, "")
if errors.Is(err, mcp.ErrUnknownProject) {
writeError(w, 400, err.Error())
return
}
if err != nil {
writeMCPFailure(w, result, err)
return
}
if err := s.reloadConfig(); err != nil {
writeError(w, 500, "MCP saved, but config reload failed")
return
}
writeJSON(w, result)
}
func (s *Server) handleMCPImport(w http.ResponseWriter, r *http.Request) {
var body struct {
From string `json:"from"`
Content string `json:"content"`
Name string `json:"name"`
// PiExtension picks one of Pi's files: pi-mcp-adapter for the adapter's, anything
// else for mcp.json. Pasted content ignores it.
PiExtension string `json:"piExtension"`
// Root reads the target's file in that mcp.projects root instead of this scope.
Root string `json:"root"`
}
if !decodeMCPRequest(w, r, &body) {
return
}
s.mu.RLock()
defer s.mu.RUnlock()
var candidates []mcp.Candidate
var err error
if body.Content != "" {
candidates, err = mcp.Import(body.From, []byte(body.Content), body.Name)
} else if body.Root != "" {
candidates, err = s.mcpService().ImportProjectClientMode(body.Root, body.From, body.PiExtension)
} else {
candidates, err = s.mcpService().ImportClientMode(body.From, body.PiExtension)
}
if err != nil {
writeError(w, 400, err.Error())
return
}
writeJSON(w, map[string]any{"candidates": candidates})
}
func (s *Server) handleMCPRestore(w http.ResponseWriter, r *http.Request) {
var body mcpRequest
if !decodeMCPRequest(w, r, &body) {
return
}
s.mu.Lock()
defer s.mu.Unlock()
service := s.mcpService()
if body.Preview {
p, err := service.PreviewRestore(body.BackupID)
if err != nil {
writeError(w, 400, err.Error())
return
}
writeJSON(w, p)
return
}
if body.Revision == "" {
writeError(w, 400, "preview before restoring")
return
}
start := time.Now()
result, err := service.Restore(body.BackupID, body.Revision)
status := "ok"
if err != nil {
status = "error"
}
s.writeOpsLog("mcp restore", status, start, map[string]any{"scope": "ui"}, "")
if err != nil {
writeMCPFailure(w, result, err)
return
}
writeJSON(w, result)
}
// browserOnServerMachine reports whether the browser runs where an editor would start. A
// reverse proxy on this machine also connects from loopback, so the Host the browser used
// must be loopback too, and a request a proxy forwarded does not count.
func browserOnServerMachine(r *http.Request) bool {
for _, header := range []string{"Forwarded", "X-Forwarded-For", "X-Real-IP"} {
if r.Header.Get(header) != "" {
return false
}
}
host, _ := splitHostPortDefault(r.Host)
host = strings.TrimSuffix(strings.Trim(host, "[]"), ".")
ip := net.ParseIP(host)
return requestFromLoopback(r) && (strings.EqualFold(host, "localhost") || ip != nil && ip.IsLoopback())
}
// handleMCPOpen opens one Agent's MCP config file, as listed by handleMCPList, the way the
// skill page opens a skill. Only those paths open, so the request cannot name another file.
func (s *Server) handleMCPOpen(w http.ResponseWriter, r *http.Request) {
// The editor starts on the machine running the server, so a viewer elsewhere on the LAN
// would launch it on someone else's screen.
if !browserOnServerMachine(r) {
writeError(w, http.StatusForbidden, "opening a file is available only on the machine running the dashboard")
return
}
var body struct {
Target string `json:"target"`
}
if !decodeMCPRequest(w, r, &body) {
return
}
s.mu.RLock()
service := s.mcpService()
source, err := mcp.LoadSource(service.ConfigPath)
path := ""
if err == nil {
path = service.ConfiguredClientPaths(source)[body.Target]
}
s.mu.RUnlock()
switch {
case err != nil:
writeError(w, 400, err.Error())
return
case path == "":
writeError(w, 400, "unknown MCP target: "+body.Target)
return
}
if _, err := os.Stat(path); err != nil {
writeError(w, 404, "config file does not exist yet: "+path)
return
}
if os.Getenv("SKILLSHARE_HEADLESS") == "1" {
writeError(w, 409, "refusing to launch editor: SKILLSHARE_HEADLESS=1")
return
}
start := time.Now()
picked, cmd, status, err := launchEditor("auto", path)
if err != nil {
writeError(w, status, err.Error())
return
}
s.writeOpsLog("mcp open", "ok", start, map[string]any{"target": body.Target, "editor": picked, "path": path, "scope": "ui"}, "")
writeJSON(w, openInEditorResponse{Editor: picked, Path: path, PID: cmd.Process.Pid})
}
func writeMCPFailure(w http.ResponseWriter, result *mcp.Result, err error) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusConflict)
message := err.Error()
if result != nil && len(result.Applied) > 0 {
message += fmt.Sprintf("; already applied: %s; backup IDs: %s", strings.Join(result.Applied, ", "), strings.Join(result.BackupIDs, ", "))
}
_ = json.NewEncoder(w).Encode(map[string]any{"error": message, "result": result})
}