Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 104 additions & 52 deletions internal/cmd/mcp/setup/setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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)
},
}

Expand All @@ -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.
Expand Down
97 changes: 97 additions & 0 deletions internal/cmd/mcp/setup/setup_test.go
Original file line number Diff line number Diff line change
@@ -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"
Expand Down Expand Up @@ -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<!-- debricked:dependency-policy:start -->\nOld policy\n<!-- debricked:dependency-policy:end -->\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<!-- debricked:dependency-policy:start -->\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) {
Expand Down
Loading
Loading