diff --git a/pkgs/mcpx/internal/mcpclient/client.go b/pkgs/mcpx/internal/mcpclient/client.go index 9aaa18580f..488c882d6c 100644 --- a/pkgs/mcpx/internal/mcpclient/client.go +++ b/pkgs/mcpx/internal/mcpclient/client.go @@ -12,6 +12,8 @@ import ( "errors" "fmt" "net/http" + "net/url" + "path/filepath" "sync" "sync/atomic" "time" @@ -122,6 +124,9 @@ type Client struct { notif Notifications // roots are the directories servers may work within. roots []Root + // root is the scope-resolved workspace root this instance serves, named + // at initialize when non-empty (decision 0004 §5). + root string // clientName and clientVersion identify mcpx on every modern request. clientName, clientVersion string // metaVersion is the version stamped into each request's _meta. Empty @@ -383,6 +388,7 @@ func newClient(ctx context.Context, t Transport, o Options) (*Client, error) { onElicit: o.OnServerRequest, onURLElicitationRequired: o.OnURLElicitationRequired, roots: append([]Root(nil), o.Roots...), + root: o.Root, modernVersions: o.ModernVersions, probeTimeout: o.ProbeTimeout, loopDone: make(chan struct{}), @@ -457,13 +463,33 @@ func (c *Client) initializeLegacy(ctx context.Context, clientName, clientVersion } func (c *Client) initializeParams() json.RawMessage { - params, _ := json.Marshal(map[string]any{ + params := map[string]any{ "protocolVersion": ProtocolVersion, // Declared only where mcpx can actually deliver; see capabilities. "capabilities": c.capabilities(false), "clientInfo": map[string]any{"name": c.clientName, "version": c.clientVersion}, - }) - return params + } + // A scope-resolved instance tells the server which workspace it serves. + // initialize params are extensible in every era, so both get the same + // fields rather than growing per-server quirks (decision 0004 §5). An + // instance with no root -- global scope, or a degraded resolution -- + // sends nothing and its initialize stays what it always was. + if uri, name, ok := c.workspaceRoot(); ok { + params["rootUri"] = uri + params["workspaceFolders"] = []map[string]any{{"uri": uri, "name": name}} + } + raw, _ := json.Marshal(params) + return raw +} + +// workspaceRoot renders the instance root as the file:// URI and folder name +// initialize carries. ok is false when the instance serves no root. +func (c *Client) workspaceRoot() (uri, name string, ok bool) { + if c.root == "" { + return "", "", false + } + u := url.URL{Scheme: "file", Path: filepath.ToSlash(c.root)} + return u.String(), filepath.Base(c.root), true } // finishLegacy records an initialize result and completes the handshake. diff --git a/pkgs/mcpx/internal/mcpclient/initialize_workspace_test.go b/pkgs/mcpx/internal/mcpclient/initialize_workspace_test.go new file mode 100644 index 0000000000..83d0c12b86 --- /dev/null +++ b/pkgs/mcpx/internal/mcpclient/initialize_workspace_test.go @@ -0,0 +1,103 @@ +package mcpclient_test + +import ( + "context" + "encoding/json" + "sync" + "testing" + "time" + + "github.com/developing-today/code/pkgs/mcpx/internal/mcpclient" +) + +// initializeParamsWithRoot connects once with the given instance root and +// returns the params of the initialize request it sent, or nil if initialize +// was answered by the modern path instead. +func initializeParamsWithRoot(t *testing.T, root string) map[string]any { + t.Helper() + f := newFake("legacy") + var ( + mu sync.Mutex + init map[string]any + first bool + ) + f.onSend = func(msg []byte) { + var frame struct { + Method string `json:"method"` + Params json.RawMessage `json:"params"` + } + if json.Unmarshal(msg, &frame) != nil || frame.Method != "initialize" { + return + } + mu.Lock() + defer mu.Unlock() + if first { + return + } + first = true + _ = json.Unmarshal(frame.Params, &init) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + c, err := mcpclient.NewWithOptions(ctx, f, mcpclient.Options{ + ClientName: "mcpx", + ClientVersion: "test", + Preference: mcpclient.PreferLegacy, + Root: root, + }) + if err != nil { + t.Fatalf("connect: %v", err) + } + defer c.Close() + mu.Lock() + defer mu.Unlock() + return init +} + +// A scope-resolved instance names its workspace at initialize, in both the +// params and the declared capability, so a workspace server (gopls) opens a +// real workspace instead of loading files ad hoc (decision 0004 §5). +func TestInitializeNamesTheScopeResolvedRoot(t *testing.T) { + params := initializeParamsWithRoot(t, "/home/user/git/code") + if params == nil { + t.Fatal("no initialize params captured") + } + if got, want := params["rootUri"], "file:///home/user/git/code"; got != want { + t.Errorf("rootUri = %v, want %v", got, want) + } + folders, ok := params["workspaceFolders"].([]any) + if !ok || len(folders) != 1 { + t.Fatalf("workspaceFolders = %v, want one folder", params["workspaceFolders"]) + } + folder, _ := folders[0].(map[string]any) + if folder["uri"] != "file:///home/user/git/code" { + t.Errorf("workspaceFolders[0].uri = %v", folder["uri"]) + } + if folder["name"] != "code" { + t.Errorf("workspaceFolders[0].name = %v, want the base name of the root", folder["name"]) + } + + caps, _ := params["capabilities"].(map[string]any) + workspace, _ := caps["workspace"].(map[string]any) + if workspace["workspaceFolders"] != true { + t.Errorf("capabilities.workspace = %v, want workspaceFolders declared true", caps["workspace"]) + } +} + +// A global-scoped (or otherwise rootless) instance sends no workspace fields +// and declares no workspace capability: no fabricated daemon-cwd root. +func TestInitializeWithoutARootIsUnchanged(t *testing.T) { + params := initializeParamsWithRoot(t, "") + if params == nil { + t.Fatal("no initialize params captured") + } + for _, key := range []string{"rootUri", "workspaceFolders"} { + if v, ok := params[key]; ok { + t.Errorf("%s = %v, want it absent for a rootless instance", key, v) + } + } + caps, _ := params["capabilities"].(map[string]any) + if v, ok := caps["workspace"]; ok { + t.Errorf("capabilities.workspace = %v, want it absent for a rootless instance", v) + } +} diff --git a/pkgs/mcpx/internal/mcpclient/modern.go b/pkgs/mcpx/internal/mcpclient/modern.go index 187619264a..cfaa72c7da 100644 --- a/pkgs/mcpx/internal/mcpclient/modern.go +++ b/pkgs/mcpx/internal/mcpclient/modern.go @@ -39,6 +39,13 @@ type Options struct { // Roots are the directories servers may work within, served from the // first request rather than from whenever they happen to be set. Roots []Root + // Root is the scope-resolved workspace root this instance serves. When + // non-empty, initialize names it as rootUri and workspaceFolders and + // declares workspace.workspaceFolders, so workspace servers (gopls) + // open a real workspace instead of loading files ad hoc (decision + // 0004 §5). Empty leaves initialize byte-for-byte as it was: a + // global-scoped instance must not fabricate a daemon-cwd root. + Root string // Cached is the era this server configuration was last found to speak, // tried first in place of the preference's order. Ignored when the // preference forces an era. @@ -103,6 +110,13 @@ func (c *Client) capabilities(modern bool) map[string]any { "elicitation": elicitation, "roots": map[string]any{"listChanged": false}, } + // A scope-resolved instance serves a workspace, so it declares the + // capability that says so (decision 0004 §5). Instances without a root + // declare nothing extra: the capability would promise a workspace that + // initialize never names. + if c.root != "" { + caps["workspace"] = map[string]any{"workspaceFolders": true} + } if modern { caps["roots"] = map[string]any{} // The 2026 extensions map (register CAP-11): {} declares support diff --git a/pkgs/mcpx/internal/pool/pool.go b/pkgs/mcpx/internal/pool/pool.go index 2d44e7fd05..e03ca25879 100644 --- a/pkgs/mcpx/internal/pool/pool.go +++ b/pkgs/mcpx/internal/pool/pool.go @@ -639,7 +639,7 @@ func (p *Pool) startLane(ctx context.Context, legacy bool, rs config.ResolvedSco case pref == mcpclient.PreferFollow: pref = mcpclient.PreferModern } - opts := mcpclient.Options{ClientName: "mcpx", ClientVersion: Version, Preference: pref} + opts := mcpclient.Options{ClientName: "mcpx", ClientVersion: Version, Preference: pref, Root: rs.Root} ref := &instanceRef{p: p} p.installServerHooks(&opts, ref) eraKey := Identity(p.cfg)