diff --git a/internal/cmd/mcp/setup/setup.go b/internal/cmd/mcp/setup/setup.go index 5eabbc7e..b8680bc1 100644 --- a/internal/cmd/mcp/setup/setup.go +++ b/internal/cmd/mcp/setup/setup.go @@ -24,14 +24,14 @@ var verifyFn = server.VerifyAccessToken var lookPathFn = exec.LookPath // NewSetupCmd creates the `mcp setup` command, which adds a debricked MCP server -// entry to a supported client's config file. +// entry to a supported client's config file and installs project instructions. func NewSetupCmd(accessToken *string, authenticator auth.IAuthenticator, baseURL string, fs io.IFileSystem, env mcpclient.IEnvironment) *cobra.Command { var clientFlag string var global bool cmd := &cobra.Command{ Use: "setup", - Short: "Add the Debricked MCP server to a client's configuration.", + Short: "Configure the Debricked MCP server and project dependency policy instructions.", Long: `Add a "debricked" MCP server entry to a supported client's configuration file (VS Code, Claude Desktop, or Cursor), so it can be picked up without hand-editing JSON. @@ -40,59 +40,18 @@ By default, VS Code and Cursor are configured at the project level (./.vscode/mc user-level config instead. Claude Desktop only has a global configuration; --global has no effect for it. +Dependency policy instructions are always installed in the current project: +VS Code: .github/copilot-instructions.md +Claude: CLAUDE.md +Cursor: .cursor/rules/debricked.mdc (always applied) +Existing instructions are preserved; rerunning setup refreshes the managed policy block. +CLAUDE.md is read by Claude Code, not automatically by Claude Desktop; for Desktop, +copy the policy into your project's instructions manually. + No access token is ever written to the config file. Run 'debricked auth login' beforehand so the server can authenticate when your MCP client starts it.`, RunE: func(cmd *cobra.Command, _ []string) error { - cmd.SilenceUsage = true - - client, err := mcpclient.ParseClient(clientFlag) - if err != nil { - return cmderror.CommandError{Code: 1, Err: err} - } - - if global && client == mcpclient.ClientClaude { - _, _ = fmt.Fprintln(cmd.ErrOrStderr(), "note: Claude Desktop only has a global configuration; --global has no effect.") - } - - path, err := mcpclient.ConfigPath(client, global, env) - if err != nil { - return cmderror.CommandError{Code: 1, Err: err} - } - - config, existed, err := mcpclient.ReadConfig(fs, path) - if err != nil { - return cmderror.CommandError{Code: 1, Err: err} - } - - command, portable := resolveCommand(env) - fields := map[string]any{ - "type": "stdio", - "command": command, - "args": []string{"mcp", "start"}, - } - - changed := mcpclient.UpsertServerEntry(config, mcpclient.ServerMapKey(client), mcpclient.ServerEntryName, fields) - if !changed { - _, _ = fmt.Fprintf(cmd.OutOrStdout(), "%s Already configured at %s, no changes made.\n", color.GreenString("✔"), path) - - return nil - } - - if err := mcpclient.WriteConfig(fs, path, config, existed); err != nil { - return cmderror.CommandError{Code: 1, Err: err} - } - - if existed { - _, _ = fmt.Fprintf(cmd.OutOrStdout(), "Backed up previous config to %s%s\n", path, mcpclient.BackupSuffix) - } - if !portable { - _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "note: %q was not found on PATH, using the current binary's absolute path instead. This is machine-specific and won't survive a reinstall or move.\n", "debricked") - } - _, _ = fmt.Fprintf(cmd.OutOrStdout(), "%s Configured %s at %s\n", color.GreenString("✔"), client, path) - - warnIfNoCredentials(cmd, accessToken, authenticator, baseURL) - - return nil + return runSetup(cmd, clientFlag, global, accessToken, authenticator, baseURL, fs, env) }, } @@ -103,6 +62,99 @@ so the server can authenticate when your MCP client starts it.`, return cmd } +func runSetup(cmd *cobra.Command, clientFlag string, global bool, accessToken *string, authenticator auth.IAuthenticator, baseURL string, fs io.IFileSystem, env mcpclient.IEnvironment) error { + cmd.SilenceUsage = true + + client, err := mcpclient.ParseClient(clientFlag) + if err != nil { + return cmderror.CommandError{Code: 1, Err: err} + } + + if global && client == mcpclient.ClientClaude { + _, _ = fmt.Fprintln(cmd.ErrOrStderr(), "note: Claude Desktop only has a global configuration; --global has no effect.") + } + + path, instructionsPath, err := resolveSetupPaths(client, global, env) + if err != nil { + return cmderror.CommandError{Code: 1, Err: err} + } + + changed, err := configureServer(cmd, client, path, fs, env) + if err != nil { + return cmderror.CommandError{Code: 1, Err: err} + } + + if err := installInstructions(cmd, client, instructionsPath, fs); err != nil { + return cmderror.CommandError{Code: 1, Err: err} + } + if client == mcpclient.ClientClaude { + _, _ = fmt.Fprintln(cmd.ErrOrStderr(), "note: CLAUDE.md is read by Claude Code, not automatically by Claude Desktop; copy the policy into your Desktop project's instructions manually.") + } + if changed { + warnIfNoCredentials(cmd, accessToken, authenticator, baseURL) + } + + return nil +} + +func resolveSetupPaths(client mcpclient.Client, global bool, env mcpclient.IEnvironment) (configPath, instructionsPath string, err error) { + configPath, err = mcpclient.ConfigPath(client, global, env) + if err != nil { + return "", "", err + } + + instructionsPath, err = mcpclient.InstructionsPath(client, env) + + return configPath, instructionsPath, err +} + +func configureServer(cmd *cobra.Command, client mcpclient.Client, path string, fs io.IFileSystem, env mcpclient.IEnvironment) (bool, error) { + config, existed, err := mcpclient.ReadConfig(fs, path) + if err != nil { + return false, err + } + + command, portable := resolveCommand(env) + fields := map[string]any{ + "type": "stdio", + "command": command, + "args": []string{"mcp", "start"}, + } + + changed := mcpclient.UpsertServerEntry(config, mcpclient.ServerMapKey(client), mcpclient.ServerEntryName, fields) + if !changed { + _, _ = fmt.Fprintf(cmd.OutOrStdout(), "%s MCP server already configured at %s, no config changes made.\n", color.GreenString("✔"), path) + + return false, nil + } + if err := mcpclient.WriteConfig(fs, path, config, existed); err != nil { + return false, err + } + if existed { + _, _ = fmt.Fprintf(cmd.OutOrStdout(), "Backed up previous config to %s%s\n", path, mcpclient.BackupSuffix) + } + if !portable { + _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "note: %q was not found on PATH, using the current binary's absolute path instead. This is machine-specific and won't survive a reinstall or move.\n", "debricked") + } + _, _ = fmt.Fprintf(cmd.OutOrStdout(), "%s Configured %s at %s\n", color.GreenString("✔"), client, path) + + return true, nil +} + +func installInstructions(cmd *cobra.Command, client mcpclient.Client, path string, fs io.IFileSystem) error { + changed, _, err := mcpclient.SetupInstructions(fs, path, client) + if err != nil { + return err + } + if changed { + _, _ = fmt.Fprintf(cmd.OutOrStdout(), "%s Installed dependency policy instructions at %s\n", color.GreenString("✔"), path) + } else { + _, _ = fmt.Fprintf(cmd.OutOrStdout(), "%s Dependency policy instructions already up to date at %s\n", color.GreenString("✔"), path) + } + + return nil +} + // resolveCommand prefers the bare "debricked" command, which resolves via the MCP // client's own PATH and is safe to commit to a shared project config. It falls back // to the absolute path of the currently running binary if "debricked" isn't on PATH. diff --git a/internal/cmd/mcp/setup/setup_test.go b/internal/cmd/mcp/setup/setup_test.go index d2453025..a66110b3 100644 --- a/internal/cmd/mcp/setup/setup_test.go +++ b/internal/cmd/mcp/setup/setup_test.go @@ -1,12 +1,15 @@ package setup import ( + "bytes" "context" "errors" + "fmt" "os/exec" "path/filepath" "testing" + "github.com/debricked/cli/internal/mcpclient" "github.com/debricked/cli/internal/mcpclient/testdata" "github.com/debricked/fortify-sca-mcp/v26/pkg/server" "github.com/stretchr/testify/assert" @@ -105,6 +108,100 @@ func TestSetupCmdIdempotent(t *testing.T) { require.NoError(t, cmd2.Execute()) assert.NotContains(t, fs.Files, filepath.Join("/proj", ".vscode", "mcp.json")+".bak") + assert.NotContains(t, fs.Files, filepath.Join("/proj", ".github", "copilot-instructions.md")+".bak") +} + +func TestSetupCmdInstallsProjectInstructionsForEveryClientAndScope(t *testing.T) { + withStubbedVerify(t, nil) + withStubbedLookPath(t, true) + for _, tt := range []struct { + client string + path string + }{ + {"vscode", filepath.Join("/proj", ".github", "copilot-instructions.md")}, + {"claude", filepath.Join("/proj", "CLAUDE.md")}, + {"cursor", filepath.Join("/proj", ".cursor", "rules", "debricked.mdc")}, + } { + for _, global := range []bool{false, true} { + t.Run(tt.client+fmt.Sprintf("/global=%t", global), func(t *testing.T) { + fs := testdata.NewFileSystem() + token := "tok" + env := testdata.Environment{Wd: "/proj", HomeDir: "/home/test", GOOSValue: "linux"} + cmd := NewSetupCmd(&token, fakeAuthenticator{}, "https://debricked.com", fs, env) + var stderr bytes.Buffer + cmd.SetErr(&stderr) + args := []string{"--client", tt.client} + if global { + args = append(args, "--global") + } + cmd.SetArgs(args) + + require.NoError(t, cmd.Execute()) + + raw, ok := fs.Files[tt.path] + require.True(t, ok) + assert.Contains(t, string(raw), "## Dependency policy") + assert.Contains(t, string(raw), "`check_dependency_policy_compliance`") + assert.Contains(t, string(raw), "Get fresh approval before checking a different candidate list.") + assert.NotContains(t, fs.Files, tt.path+mcpclient.BackupSuffix) + if tt.client == "cursor" { + assert.Contains(t, string(raw), "---\nalwaysApply: true\n---") + } + if tt.client == "claude" { + assert.Contains(t, stderr.String(), "not automatically by Claude Desktop") + } + }) + } + } +} + +func TestSetupCmdRefreshesInstructionsWhenServerAlreadyConfigured(t *testing.T) { + withStubbedVerify(t, nil) + withStubbedLookPath(t, true) + fs := testdata.NewFileSystem() + token := "tok" + env := testdata.Environment{Wd: "/proj", GOOSValue: "linux"} + cmd := NewSetupCmd(&token, fakeAuthenticator{}, "https://debricked.com", fs, env) + cmd.SetArgs([]string{"--client", "vscode"}) + require.NoError(t, cmd.Execute()) + path := filepath.Join("/proj", ".github", "copilot-instructions.md") + original := "# My instructions\n\n\nOld policy\n\n\nKeep this.\n" + fs.Files[path] = []byte(original) + + cmd = NewSetupCmd(&token, fakeAuthenticator{}, "https://debricked.com", fs, env) + cmd.SetArgs([]string{"--client", "vscode"}) + require.NoError(t, cmd.Execute()) + + assert.Contains(t, string(fs.Files[path]), "# My instructions") + assert.Contains(t, string(fs.Files[path]), "Keep this.") + assert.Contains(t, string(fs.Files[path]), "`check_dependency_policy_compliance`") + assert.NotContains(t, string(fs.Files[path]), "Old policy") + assert.NotContains(t, fs.Files, path+mcpclient.BackupSuffix) + assert.NotContains(t, fs.Files, filepath.Join("/proj", ".vscode", "mcp.json")+mcpclient.BackupSuffix) + + delete(fs.Files, path) + cmd = NewSetupCmd(&token, fakeAuthenticator{}, "https://debricked.com", fs, env) + cmd.SetArgs([]string{"--client", "vscode"}) + require.NoError(t, cmd.Execute()) + assert.Contains(t, string(fs.Files[path]), "`check_dependency_policy_compliance`") +} + +func TestSetupCmdReportsMalformedInstructions(t *testing.T) { + withStubbedVerify(t, nil) + withStubbedLookPath(t, true) + fs := testdata.NewFileSystem() + token := "tok" + path := filepath.Join("/proj", ".github", "copilot-instructions.md") + original := "# Keep this\n\n" + fs.Files[path] = []byte(original) + cmd := NewSetupCmd(&token, fakeAuthenticator{}, "https://debricked.com", fs, testdata.Environment{Wd: "/proj"}) + cmd.SetArgs([]string{"--client", "vscode"}) + + err := cmd.Execute() + + require.ErrorContains(t, err, "invalid dependency policy markers") + assert.Equal(t, original, string(fs.Files[path])) + assert.NotContains(t, fs.Files, path+mcpclient.BackupSuffix) } func TestSetupCmdBacksUpExistingFile(t *testing.T) { diff --git a/internal/mcpclient/instructions.go b/internal/mcpclient/instructions.go new file mode 100644 index 00000000..43b41b92 --- /dev/null +++ b/internal/mcpclient/instructions.go @@ -0,0 +1,140 @@ +package mcpclient + +import ( + "fmt" + "path/filepath" + "strings" + + "github.com/debricked/cli/internal/io" +) + +const instructionStart = "" +const instructionEnd = "" + +const dependencyPolicy = "## Dependency policy\n\n" + + "Before adding, installing, upgrading, importing, or recommending a dependency, call\n" + + "`check_dependency_policy_compliance` with 1–5 distinct, versioned PURLs (`purls`); use one for a\n" + + "single package.\n\n" + + "- **Compliant:** Report the checked package/version as approved by Fortify SCA (Debricked).\n" + + "- **Blocked:** Do not add it. Report every rule's condition, package-specific trigger evidence, and\n" + + " configuration URL when present. Disclose truncated results; never infer which OR branch matched.\n" + + "- **Unavailable:** Report the reason; do not claim approval.\n" + + "- **Alternatives:** For a blocked package, inspect its use and compatibility, then present up to\n" + + " five exact, versioned PURLs as unchecked candidates. Ask approval for that exact list. After\n" + + " approval, check all approved candidates in one call. Recommend only candidates that pass; report\n" + + " each result and say if none pass. Approval permits checking only, not adding or installing.\n" + + " Get fresh approval before checking a different candidate list." + +// InstructionsPath always resolves project instructions, independently of the MCP config scope. +func InstructionsPath(client Client, env IEnvironment) (string, error) { + wd, err := env.Getwd() + if err != nil { + return "", fmt.Errorf("failed to resolve current directory: %w", err) + } + + switch client { + case ClientVSCode: + return filepath.Join(wd, ".github", "copilot-instructions.md"), nil + case ClientClaude: + return filepath.Join(wd, "CLAUDE.md"), nil + case ClientCursor: + return filepath.Join(wd, ".cursor", "rules", "debricked.mdc"), nil + default: + return "", fmt.Errorf("unsupported client %q", client) + } +} + +// SetupInstructions refreshes only the managed policy block in place. +func SetupInstructions(fs io.IFileSystem, path string, client Client) (changed, existed bool, err error) { + raw, err := fs.ReadFile(path) + if err != nil && !fs.IsNotExist(err) { + return false, false, fmt.Errorf("failed to read %s: %w", path, err) + } + existed = err == nil + + content, err := upsertInstructions(string(raw), client) + if err != nil { + return false, existed, fmt.Errorf("failed to update %s: %w", path, err) + } + if content == string(raw) { + return false, existed, nil + } + + if err := fs.MkdirAll(filepath.Dir(path), 0750); err != nil { + return false, existed, fmt.Errorf("failed to create directory for %s: %w", path, err) + } + if err := fs.FsWriteFile(path, []byte(content), 0644); err != nil { + return false, existed, fmt.Errorf("failed to write %s: %w", path, err) + } + + return true, existed, nil +} + +func upsertInstructions(content string, client Client) (string, error) { + newline := "\n" + if strings.Contains(content, "\r\n") { + newline = "\r\n" + } + block := strings.ReplaceAll(instructionStart+"\n"+dependencyPolicy+"\n"+instructionEnd, "\n", newline) + start, end := strings.Index(content, instructionStart), strings.Index(content, instructionEnd) + content, err := replaceManagedPolicy(content, block, newline, start, end) + if err != nil { + return "", err + } + if client == ClientCursor { + return alwaysApplyCursorRule(content, newline) + } + + return content, nil +} + +func replaceManagedPolicy(content, block, newline string, start, end int) (string, error) { + if start >= 0 || end >= 0 { + if !validManagedPolicyMarkers(content, start, end) { + return "", fmt.Errorf("invalid dependency policy markers; fix or remove them manually") + } + content = content[:start] + block + content[end+len(instructionEnd):] + } else { + if content != "" { + if !strings.HasSuffix(content, newline) { + content += newline + } + content += newline + } + content += block + newline + } + + return content, nil +} + +func validManagedPolicyMarkers(content string, start, end int) bool { + return start >= 0 && + end >= start && + strings.Count(content, instructionStart) == 1 && + strings.Count(content, instructionEnd) == 1 +} + +func alwaysApplyCursorRule(content, newline string) (string, error) { + delimiter := "---" + newline + if !strings.HasPrefix(content, delimiter) { + return delimiter + "alwaysApply: true" + newline + delimiter + newline + content, nil + } + + lines := strings.Split(content, newline) + for i := 1; i < len(lines); i++ { + if lines[i] == "---" { + header := make([]string, 0, i+1) + header = append(header, lines[0]) + for _, line := range lines[1:i] { + if !strings.HasPrefix(line, "alwaysApply:") { + header = append(header, line) + } + } + header = append(header, "alwaysApply: true") + + return strings.Join(append(header, lines[i:]...), newline), nil + } + } + + return "", fmt.Errorf("unterminated Cursor rule frontmatter; fix it manually") +} diff --git a/internal/mcpclient/instructions_test.go b/internal/mcpclient/instructions_test.go new file mode 100644 index 00000000..639ee31a --- /dev/null +++ b/internal/mcpclient/instructions_test.go @@ -0,0 +1,160 @@ +package mcpclient + +import ( + "errors" + stdfs "io/fs" + "path/filepath" + "strings" + "testing" + + debio "github.com/debricked/cli/internal/io" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestSetupInstructionsPreservesAndRefreshesPolicy(t *testing.T) { + for name, newline := range map[string]string{"LF": "\n", "CRLF": "\r\n"} { + t.Run(name, func(t *testing.T) { + fs := debio.FileSystem{} + path := filepath.Join(t.TempDir(), "instructions.md") + original := strings.Join([]string{ + "# Existing instructions", "", instructionStart, "outdated policy", instructionEnd, "", "Keep this too.", "", + }, newline) + require.NoError(t, fs.FsWriteFile(path, []byte(original), 0644)) + + changed, existed, err := SetupInstructions(fs, path, ClientVSCode) + + require.NoError(t, err) + assert.True(t, changed) + assert.True(t, existed) + raw, err := fs.ReadFile(path) + require.NoError(t, err) + content := string(raw) + assert.Equal(t, "# Existing instructions"+newline+newline+instructionStart+newline+ + strings.ReplaceAll(dependencyPolicy, "\n", newline)+newline+instructionEnd+ + newline+newline+"Keep this too."+newline, content) + _, err = fs.ReadFile(path + BackupSuffix) + assert.True(t, fs.IsNotExist(err)) + + changed, _, err = SetupInstructions(fs, path, ClientVSCode) + require.NoError(t, err) + assert.False(t, changed) + _, err = fs.ReadFile(path + BackupSuffix) + assert.True(t, fs.IsNotExist(err)) + }) + } +} + +func TestSetupInstructionsAppendsToExistingContent(t *testing.T) { + fs := debio.FileSystem{} + path := filepath.Join(t.TempDir(), "CLAUDE.md") + original := "# Project conventions\nKeep existing instructions." + require.NoError(t, fs.FsWriteFile(path, []byte(original), 0644)) + + changed, existed, err := SetupInstructions(fs, path, ClientClaude) + + require.NoError(t, err) + assert.True(t, changed) + assert.True(t, existed) + raw, err := fs.ReadFile(path) + require.NoError(t, err) + assert.Equal(t, original+"\n\n"+instructionStart+"\n"+dependencyPolicy+"\n"+instructionEnd+"\n", string(raw)) +} + +func TestCursorInstructionsAlwaysApply(t *testing.T) { + for _, original := range []string{ + "", + "# Existing rule", + "---\ndescription: Existing description\nglobs: \"*.go\"\nalwaysApply: false\n---\n\n# Existing rule\n", + } { + content, err := upsertInstructions(original, ClientCursor) + require.NoError(t, err) + assert.Contains(t, content, "\nalwaysApply: true\n---\n") + assert.NotContains(t, content, "alwaysApply: false") + if original != "" { + assert.Contains(t, content, "# Existing rule") + } + if strings.Contains(original, "description:") { + assert.Contains(t, content, "description: Existing description\nglobs: \"*.go\"") + } + updated, err := upsertInstructions(content, ClientCursor) + require.NoError(t, err) + assert.Equal(t, content, updated) + } +} + +func TestSetupInstructionsRejectsMalformedManagedContent(t *testing.T) { + for _, original := range []string{ + instructionStart, + instructionEnd, + instructionEnd + "\n" + instructionStart, + instructionStart + instructionStart + instructionEnd, + instructionStart + instructionEnd + instructionEnd, + "---\nalwaysApply: false\n", + } { + fs := debio.FileSystem{} + path := filepath.Join(t.TempDir(), "debricked.mdc") + require.NoError(t, fs.FsWriteFile(path, []byte(original), 0644)) + + _, _, err := SetupInstructions(fs, path, ClientCursor) + + require.Error(t, err) + raw, err := fs.ReadFile(path) + require.NoError(t, err) + assert.Equal(t, original, string(raw)) + _, err = fs.ReadFile(path + BackupSuffix) + assert.True(t, fs.IsNotExist(err)) + } +} + +type failingInstructionsFS struct { + debio.IFileSystem + readErr error + mkdirErr error + writeErr error +} + +func (f failingInstructionsFS) ReadFile(path string) ([]byte, error) { + if f.readErr != nil { + return nil, f.readErr + } + + return f.IFileSystem.ReadFile(path) +} + +func (f failingInstructionsFS) MkdirAll(path string, perm stdfs.FileMode) error { + if f.mkdirErr != nil { + return f.mkdirErr + } + + return f.IFileSystem.MkdirAll(path, perm) +} + +func (f failingInstructionsFS) FsWriteFile(path string, raw []byte, perm stdfs.FileMode) error { + if f.writeErr != nil { + return f.writeErr + } + + return f.IFileSystem.FsWriteFile(path, raw, perm) +} + +func TestSetupInstructionsSurfacesFileErrors(t *testing.T) { + failure := errors.New("permission denied") + for _, fs := range []failingInstructionsFS{ + {readErr: failure}, + {mkdirErr: failure}, + {writeErr: failure}, + } { + fs.IFileSystem = debio.FileSystem{} + path := filepath.Join(t.TempDir(), "instructions.md") + require.NoError(t, fs.IFileSystem.FsWriteFile(path, []byte("Existing instructions"), 0644)) + + changed, _, err := SetupInstructions(fs, path, ClientVSCode) + + assert.ErrorIs(t, err, failure) + assert.False(t, changed) + raw, err := fs.IFileSystem.ReadFile(path) + require.NoError(t, err) + assert.Equal(t, "Existing instructions", string(raw)) + } +}