Files
skillshare/internal/server/handler_mcp.go
T
Willie bfc402fe96 feat(mcp): open an Agent's MCP config folder, and project files, from the dashboard (#554)
* feat(mcp): open an Agent's MCP config folder, and project files, from the dashboard

A user who wants their own editor (Notepad++ on Windows) found setting
both PATH and $EDITOR too much just to open a config file, and could not
find any entry point for the MCP files of an mcp.projects root (#538).

Each Agent row on the MCP page now also has Open folder, which opens the
folder holding the file in the file manager, so any program can open it
from there. Before the Agent has written its file, it opens the closest
folder that exists. The project MCP tab gets the same Agents list for
that project's files. The open endpoint resolves project paths from the
config, as it does global ones, so a request still cannot name another
file, and folder and file opens keep the same-machine and headless
guards. The file manager launch is shared with the extensions folder.

* fix(mcp): keep a project's existing Agent files listed for remote viewers

Codex review: the project MCP tab built its Agents list from the
project's targets plus the files this viewer could open. A viewer on a
LAN address or behind a proxy can open none, so an existing file of an
Agent outside the project's targets dropped off the list, although the
docs say it shows with its path and only the open buttons go.

The list now returns which files exist apart from whether this viewer
may open them, and the page shows the open buttons only when local.

* fix(mcp): list the Agents a project's own servers write to in its file rail

Codex review: a server that exists only in one project can pick Agents
outside the project's targets, and sync writes their project files, but
the project tab listed only the project's targets and files that already
existed. Before the first sync such an Agent had no row, so its path
could not be copied and its folder could not be opened.

The list now also takes the targets of the project's own servers. Global
servers reach a project only through its targets, so they add nothing.
The rule lives in mcpView as projectFileTargets, with a unit test.
2026-10-13 15:00:39 +08:00

405 lines
12 KiB
Go

package server
import (
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"os"
"path/filepath"
"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.
local := browserOnServerMachine(r)
openable := []string{}
if local {
openable = existingTargets(paths)
}
// Each mcp.projects root's files, which the project page lists for every viewer and offers
// to open when local. handleMCPOpen refuses those roots in project mode.
projectPaths, projectExisting := map[string]map[string]string{}, map[string][]string{}
if !s.IsProjectMode() {
for root := range source.Projects {
projectPaths[root] = service.ForProject(root).ClientPaths()
projectExisting[root] = existingTargets(projectPaths[root])
}
}
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, "local": local, "openable": openable, "projectPaths": projectPaths, "projectExisting": projectExisting, "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())
}
// existingTargets lists the targets whose file exists.
func existingTargets(paths map[string]string) []string {
out := []string{}
for target, path := range paths {
if _, err := os.Stat(path); err == nil {
out = append(out, target)
}
}
slices.Sort(out)
return out
}
// mcpOpenPath resolves target's file as handleMCPList lists it, in this scope or in one
// mcp.projects root, so a request cannot name another file.
func (s *Server) mcpOpenPath(target, project string) (string, error) {
s.mu.RLock()
defer s.mu.RUnlock()
service := s.mcpService()
source, err := mcp.LoadSource(service.ConfigPath)
if err != nil {
return "", err
}
var paths map[string]string
if project == "" {
paths = service.ConfiguredClientPaths(source)
} else if _, ok := source.Projects[project]; ok && !s.IsProjectMode() {
paths = service.ForProject(project).ClientPaths()
} else {
return "", fmt.Errorf("unknown MCP project: %s", project)
}
if paths[target] == "" {
return "", fmt.Errorf("unknown MCP target: %s", target)
}
return paths[target], nil
}
// nearestDir returns dir, or its closest parent that exists.
func nearestDir(dir string) string {
for {
if _, err := os.Stat(dir); err == nil || filepath.Dir(dir) == dir {
return dir
}
dir = filepath.Dir(dir)
}
}
// handleMCPOpen opens one Agent's MCP config file the way the skill page opens a skill, or
// with folder the folder that holds it in the file manager.
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"`
Project string `json:"project"`
Folder bool `json:"folder"`
}
if !decodeMCPRequest(w, r, &body) {
return
}
path, err := s.mcpOpenPath(body.Target, body.Project)
if err != nil {
writeError(w, 400, err.Error())
return
}
start := time.Now()
if body.Folder {
// Before the Agent writes its file, its folder may not exist either.
dir := nearestDir(filepath.Dir(path))
if status, err := openFileManager(dir); err != nil {
writeError(w, status, err.Error())
return
}
s.writeOpsLog("mcp open", "ok", start, map[string]any{"target": body.Target, "project": body.Project, "path": dir, "scope": "ui"}, "")
writeJSON(w, map[string]any{"path": dir})
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
}
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, "project": body.Project, "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})
}