diff --git a/cmd/aitools/list_test.go b/cmd/aitools/list_test.go index 257300846c2..31234a62d49 100644 --- a/cmd/aitools/list_test.go +++ b/cmd/aitools/list_test.go @@ -624,3 +624,29 @@ func TestListScopeFlag(t *testing.T) { }) } } + +// TestLoadStateForScopeIgnoresMCPOnlyState checks that a state file holding only MCP records is not an +// install of skills or plugins, so the scope is not reported as loaded. +func TestLoadStateForScopeIgnoresMCPOnlyState(t *testing.T) { + ctx := env.WithUserHomeDir(t.Context(), t.TempDir()) + dir, err := installer.GlobalSkillsDir(ctx) + require.NoError(t, err) + require.NoError(t, installer.SaveMCPState(dir, &installer.MCPState{Servers: []installer.MCPEntry{{Name: "github-logfood"}}})) + + state := loadStateForScope(ctx, "", installer.ScopeProject, installer.GlobalSkillsDir, "global") + assert.Nil(t, state) +} + +// TestLoadStateForScopeKeepsSkillsState checks that a state file with skills is loaded, with or without +// MCP records next to them. +func TestLoadStateForScopeKeepsSkillsState(t *testing.T) { + ctx := env.WithUserHomeDir(t.Context(), t.TempDir()) + dir, err := installer.GlobalSkillsDir(ctx) + require.NoError(t, err) + require.NoError(t, installer.SaveState(dir, &installer.InstallState{SchemaVersion: installer.CurrentSchemaVersion, Skills: map[string]string{"databricks": "1.0.0"}})) + require.NoError(t, installer.SaveMCPState(dir, &installer.MCPState{Servers: []installer.MCPEntry{{Name: "github-logfood"}}})) + + state := loadStateForScope(ctx, "", installer.ScopeProject, installer.GlobalSkillsDir, "global") + require.NotNil(t, state) + assert.Equal(t, "1.0.0", state.Skills["databricks"]) +} diff --git a/cmd/aitools/scope_test.go b/cmd/aitools/scope_test.go index da941dbb316..1b5a47b92f2 100644 --- a/cmd/aitools/scope_test.go +++ b/cmd/aitools/scope_test.go @@ -620,3 +620,18 @@ func TestResolveScopeForUpdateProjectFlagHintsUpdate(t *testing.T) { require.Error(t, err) assert.Contains(t, err.Error(), "with --scope=global to update those") } + +// TestDetectInstalledScopesIgnoresMCPOnlyState checks that MCP records alone do not make a scope +// installed. +func TestDetectInstalledScopesIgnoresMCPOnlyState(t *testing.T) { + globalDir, projectDir := setupScopeTest(t) + require.NoError(t, installer.SaveMCPState(globalDir, &installer.MCPState{Servers: []installer.MCPEntry{{Name: "github-logfood"}}})) + + hasGlobal, hasProject, err := detectInstalledScopes(globalDir, projectDir) + require.NoError(t, err) + assert.False(t, hasGlobal) + assert.False(t, hasProject) + + _, err = withExplicitScopeCheck(globalDir, installer.ScopeGlobal, "update", projectDir, false, false) + assert.Error(t, err) +} diff --git a/cmd/aitools/uninstall_test.go b/cmd/aitools/uninstall_test.go index 6314254d727..ba9b30ae487 100644 --- a/cmd/aitools/uninstall_test.go +++ b/cmd/aitools/uninstall_test.go @@ -133,3 +133,17 @@ func TestUninstallConfirmMessage(t *testing.T) { require.True(t, ask3) assert.Contains(t, msg3, "from cursor") } + +// TestUninstallConfirmMessageMCPOnlyState checks that an explicit skill list does not prompt when +// the state file holds only MCP records, as loaded for uninstall. +func TestUninstallConfirmMessageMCPOnlyState(t *testing.T) { + dir := t.TempDir() + require.NoError(t, installer.SaveMCPState(dir, &installer.MCPState{Servers: []installer.MCPEntry{{Name: "github-logfood"}}})) + st, err := installer.LoadState(dir) + require.NoError(t, err) + + _, ask := uninstallConfirmMessage(st, installer.UninstallOptions{Scope: installer.ScopeGlobal}) + assert.False(t, ask) + _, ask = uninstallConfirmMessage(st, installer.UninstallOptions{Scope: installer.ScopeGlobal, Skills: []string{"databricks-sql"}}) + assert.False(t, ask) +} diff --git a/cmd/aitools/update_test.go b/cmd/aitools/update_test.go index 74e869213ac..ad6ad104776 100644 --- a/cmd/aitools/update_test.go +++ b/cmd/aitools/update_test.go @@ -616,3 +616,21 @@ func TestUpdateWithoutStateKeepsTheInstallGuidance(t *testing.T) { err := cmd.Execute() require.ErrorIs(t, err, installer.ErrNothingInstalled) } + +// TestUpdateMCPOnlyStateReachesSkillsUpdate checks that a state file holding only MCP records still +// runs the skills update, which reports that nothing is installed. +func TestUpdateMCPOnlyStateReachesSkillsUpdate(t *testing.T) { + home := setupTestAgents(t) + t.Setenv("DATABRICKS_SKILLS_REF", "v0.2.6") + calls := setupUpdateMock(t) + + globalDir := filepath.Join(home, ".databricks", "aitools", "skills") + require.NoError(t, installer.SaveMCPState(globalDir, &installer.MCPState{Servers: []installer.MCPEntry{{Name: "github-logfood"}}})) + + ctx, _ := cmdio.NewTestContextWithStderr(t.Context()) + cmd := NewUpdateCmd() + cmd.SetContext(ctx) + cmd.SetArgs([]string{"--scope", "global", "--check"}) + require.NoError(t, cmd.Execute()) + assert.Len(t, *calls, 1) +} diff --git a/cmd/aitools/version_test.go b/cmd/aitools/version_test.go index cf4a6516e0a..cf4b25755d8 100644 --- a/cmd/aitools/version_test.go +++ b/cmd/aitools/version_test.go @@ -157,3 +157,23 @@ func TestVersionAlwaysLabelsScope(t *testing.T) { assert.Contains(t, output, "Skills (global): v0.1.0") assert.NotContains(t, output, "Skills (project)") } + +// TestVersionMCPOnlyStateReportsNothingInstalled checks that a state file holding only MCP records +// is reported as having no skills or plugins. +func TestVersionMCPOnlyStateReportsNothingInstalled(t *testing.T) { + tmp := t.TempDir() + t.Setenv("HOME", tmp) + t.Setenv("USERPROFILE", tmp) + t.Chdir(tmp) + + globalDir := filepath.Join(tmp, ".databricks", "aitools", "skills") + require.NoError(t, installer.SaveMCPState(globalDir, &installer.MCPState{Servers: []installer.MCPEntry{{Name: "github-logfood"}}})) + + ctx, stderr := cmdio.NewTestContextWithStderr(t.Context()) + cmd := NewVersionCmd() + cmd.SetContext(ctx) + require.NoError(t, cmd.RunE(cmd, nil)) + + assert.Contains(t, stderr.String(), "No Databricks skills or plugins installed.") + assert.NotContains(t, stderr.String(), "Databricks skills and plugins:") +} diff --git a/libs/aitools/installer/cleanup_test.go b/libs/aitools/installer/cleanup_test.go index b19d6272653..4acc11dac88 100644 --- a/libs/aitools/installer/cleanup_test.go +++ b/libs/aitools/installer/cleanup_test.go @@ -51,7 +51,7 @@ func TestRemoveLegacyRawSkills(t *testing.T) { require.NoError(t, os.WriteFile(filepath.Join(agentDir, "delta", "extra.md"), []byte("mine"), 0o644)) require.NoError(t, SaveState(baseDir, &InstallState{ - SchemaVersion: schemaVersionV2, + SchemaVersion: CurrentSchemaVersion, Files: map[string]FileRecord{ "alpha/SKILL.md": {SHA256: sha("alpha")}, "beta/SKILL.md": {SHA256: sha("beta-content")}, @@ -93,7 +93,7 @@ func TestHasManagedRawSkillsForAgent(t *testing.T) { require.NoError(t, os.WriteFile(filepath.Join(agentDir, "thirdparty", "SKILL.md"), []byte("mine"), 0o644)) require.NoError(t, SaveState(baseDir, &InstallState{ - SchemaVersion: schemaVersionV2, + SchemaVersion: CurrentSchemaVersion, Files: map[string]FileRecord{ "alpha/SKILL.md": {SHA256: sha("alpha")}, }, diff --git a/libs/aitools/installer/detect_test.go b/libs/aitools/installer/detect_test.go index b5ab58f3191..5c52d8b0b37 100644 --- a/libs/aitools/installer/detect_test.go +++ b/libs/aitools/installer/detect_test.go @@ -171,7 +171,7 @@ func savePluginState(t *testing.T, dirFn func(context.Context) (string, error), dir, err := dirFn(t.Context()) require.NoError(t, err) require.NoError(t, SaveState(dir, &InstallState{ - SchemaVersion: schemaVersionV2, + SchemaVersion: CurrentSchemaVersion, Plugins: plugins, })) } diff --git a/libs/aitools/installer/installer.go b/libs/aitools/installer/installer.go index fa30d4537ec..8e5115a1998 100644 --- a/libs/aitools/installer/installer.go +++ b/libs/aitools/installer/installer.go @@ -444,7 +444,7 @@ func InstallSkillsForAgents(ctx context.Context, src ManifestSource, targetAgent // previous installs (e.g., experimental skills from a prior run) are preserved. if state == nil { state = &InstallState{ - SchemaVersion: schemaVersionV2, + SchemaVersion: CurrentSchemaVersion, Skills: make(map[string]string, len(targetSkills)), RepoDirs: make(map[string]string, len(targetSkills)), } diff --git a/libs/aitools/installer/installer_test.go b/libs/aitools/installer/installer_test.go index 959029d23c6..0c8c86b42d1 100644 --- a/libs/aitools/installer/installer_test.go +++ b/libs/aitools/installer/installer_test.go @@ -442,7 +442,7 @@ func TestInstallSkillsForAgentsWritesState(t *testing.T) { state, err := LoadState(globalDir) require.NoError(t, err) require.NotNil(t, state) - assert.Equal(t, schemaVersionV2, state.SchemaVersion) + assert.Equal(t, CurrentSchemaVersion, state.SchemaVersion) assert.Equal(t, testSkillsRef, state.Release) assert.Len(t, state.Skills, 2) assert.Equal(t, "0.1.0", state.Skills["databricks-sql"]) @@ -1654,3 +1654,40 @@ func TestInstallAllSkillsWithNoSkillToInstall(t *testing.T) { require.NoError(t, InstallAllSkills(ctx)) assert.Contains(t, stderr.String(), NoSkillsResolvedMessage) } + +// TestLegacyTargetedInstallBlockedWithMCPOnlyState checks that MCP records in the state file do not +// count as tracked skills, so skills on disk without a skills record still block a targeted install. +func TestLegacyTargetedInstallBlockedWithMCPOnlyState(t *testing.T) { + tmp := setupTestHome(t) + ctx := cmdio.MockDiscard(t.Context()) + setupFetchMock(t) + t.Setenv("DATABRICKS_SKILLS_REF", testSkillsRef) + + globalDir := filepath.Join(tmp, ".databricks", "aitools", "skills") + require.NoError(t, os.MkdirAll(filepath.Join(globalDir, "databricks-sql"), 0o755)) + require.NoError(t, SaveMCPState(globalDir, &MCPState{Servers: []MCPEntry{{Name: "github-logfood"}}})) + + src := &mockManifestSource{manifest: testManifest()} + err := InstallSkillsForAgents(ctx, src, []*agents.Agent{testAgent(tmp)}, InstallOptions{ + SpecificSkills: []string{"databricks-sql"}, + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "legacy install detected") +} + +// TestInstallSpecificSkillWithEmptyStateFile checks that an empty state file, as an update that pruned +// every skill leaves, does not count as a legacy install, so a targeted install still runs. +func TestInstallSpecificSkillWithEmptyStateFile(t *testing.T) { + tmp := setupTestHome(t) + ctx := cmdio.MockDiscard(t.Context()) + setupFetchMock(t) + t.Setenv("DATABRICKS_SKILLS_REF", testSkillsRef) + globalDir := filepath.Join(tmp, ".databricks", "aitools", "skills") + require.NoError(t, os.MkdirAll(filepath.Join(globalDir, "databricks-old"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(globalDir, ".state.json"), []byte(`{"schema_version": 2, "skills": {}}`+"\n"), 0o600)) + + err := InstallSkillsForAgents(ctx, &mockManifestSource{manifest: testManifest()}, []*agents.Agent{testAgent(tmp)}, InstallOptions{ + SpecificSkills: []string{"databricks-sql"}, + }) + require.NoError(t, err) +} diff --git a/libs/aitools/installer/plugin.go b/libs/aitools/installer/plugin.go index d623a75c496..51cb0b2fce2 100644 --- a/libs/aitools/installer/plugin.go +++ b/libs/aitools/installer/plugin.go @@ -510,7 +510,7 @@ func RecordPluginInstalls(ctx context.Context, cliScope string, records map[stri // Initialize all maps so a later skills install/update can assign into a // plugin-only state without hitting a nil map. state = &InstallState{ - SchemaVersion: schemaVersionV2, + SchemaVersion: CurrentSchemaVersion, Skills: map[string]string{}, RepoDirs: map[string]string{}, Files: map[string]FileRecord{}, diff --git a/libs/aitools/installer/plugin_test.go b/libs/aitools/installer/plugin_test.go index 645dec6a853..09120d406fe 100644 --- a/libs/aitools/installer/plugin_test.go +++ b/libs/aitools/installer/plugin_test.go @@ -380,7 +380,7 @@ func TestUninstallSkillsWithResultTearsDownPlugin(t *testing.T) { dir, err := GlobalSkillsDir(ctx) require.NoError(t, err) require.NoError(t, SaveState(dir, &InstallState{ - SchemaVersion: schemaVersionV2, + SchemaVersion: CurrentSchemaVersion, Release: "v0.2.6", Plugins: map[string]PluginRecord{ agents.NameCopilot: {Marketplace: "databricks-agent-skills", Plugin: "databricks", Scope: "user", InstalledMarketplace: true}, @@ -411,7 +411,7 @@ func TestUninstallSkillsWithResultTargetsPluginAgents(t *testing.T) { dir, err := GlobalSkillsDir(ctx) require.NoError(t, err) require.NoError(t, SaveState(dir, &InstallState{ - SchemaVersion: schemaVersionV2, + SchemaVersion: CurrentSchemaVersion, Release: "v0.2.6", Plugins: map[string]PluginRecord{ agents.NameClaudeCode: {Marketplace: "claude-plugins-official", Plugin: "databricks", Scope: "user"}, @@ -447,7 +447,7 @@ func TestUninstallNeverDeregistersSharedMarketplace(t *testing.T) { // Claude's claude-plugins-official is a Shared marketplace; even a stale // InstalledMarketplace=true must never trigger a de-register. require.NoError(t, SaveState(dir, &InstallState{ - SchemaVersion: schemaVersionV2, + SchemaVersion: CurrentSchemaVersion, Plugins: map[string]PluginRecord{ agents.NameClaudeCode: {Marketplace: "claude-plugins-official", Plugin: "databricks", InstalledMarketplace: true}, }, @@ -476,7 +476,7 @@ func TestUninstallKeepMarketplace(t *testing.T) { dir, err := GlobalSkillsDir(ctx) require.NoError(t, err) require.NoError(t, SaveState(dir, &InstallState{ - SchemaVersion: schemaVersionV2, + SchemaVersion: CurrentSchemaVersion, Plugins: map[string]PluginRecord{ agents.NameCopilot: {Marketplace: "databricks-agent-skills", Plugin: "databricks", InstalledMarketplace: true}, }, @@ -497,7 +497,7 @@ func TestUninstallKeepsUnknownAgentRecord(t *testing.T) { dir, err := GlobalSkillsDir(ctx) require.NoError(t, err) require.NoError(t, SaveState(dir, &InstallState{ - SchemaVersion: schemaVersionV2, + SchemaVersion: CurrentSchemaVersion, Plugins: map[string]PluginRecord{ "mystery-agent": {Marketplace: "databricks-agent-skills", Plugin: "databricks"}, }, @@ -526,7 +526,7 @@ func TestUninstallClearsRecordWhenMarketplaceRemoveFails(t *testing.T) { dir, err := GlobalSkillsDir(ctx) require.NoError(t, err) require.NoError(t, SaveState(dir, &InstallState{ - SchemaVersion: schemaVersionV2, + SchemaVersion: CurrentSchemaVersion, Plugins: map[string]PluginRecord{ agents.NameCopilot: {Marketplace: "databricks-agent-skills", Plugin: "databricks", InstalledMarketplace: true}, }, @@ -551,7 +551,7 @@ func TestUpdateInstalledPlugins(t *testing.T) { dir, err := GlobalSkillsDir(ctx) require.NoError(t, err) require.NoError(t, SaveState(dir, &InstallState{ - SchemaVersion: schemaVersionV2, + SchemaVersion: CurrentSchemaVersion, Release: "v0.2.6", Plugins: map[string]PluginRecord{ agents.NameCopilot: {Marketplace: "databricks-agent-skills", Plugin: "databricks", Scope: "user", Version: "0.2.6"}, @@ -596,7 +596,7 @@ func TestUpdateInstalledPluginsRecordsUnknownVersionWhenRefreshFails(t *testing. dir, err := GlobalSkillsDir(ctx) require.NoError(t, err) require.NoError(t, SaveState(dir, &InstallState{ - SchemaVersion: schemaVersionV2, + SchemaVersion: CurrentSchemaVersion, Release: "v" + tc.recorded, Plugins: map[string]PluginRecord{ agents.NameClaudeCode: {Marketplace: "claude-plugins-official", Plugin: "databricks", Scope: "user", Version: tc.recorded}, @@ -635,7 +635,7 @@ func TestUpdateInstalledPluginsUsesRecordedClaudeScope(t *testing.T) { dir, err := GlobalSkillsDir(ctx) require.NoError(t, err) require.NoError(t, SaveState(dir, &InstallState{ - SchemaVersion: schemaVersionV2, + SchemaVersion: CurrentSchemaVersion, Release: "v0.2.6", Plugins: map[string]PluginRecord{ agents.NameClaudeCode: {Marketplace: "claude-plugins-official", Plugin: "databricks", Scope: scope, Version: "0.2.6"}, @@ -729,7 +729,7 @@ func saveUnknownAgentPlugin(t *testing.T) (context.Context, string) { dir, err := GlobalSkillsDir(ctx) require.NoError(t, err) require.NoError(t, SaveState(dir, &InstallState{ - SchemaVersion: schemaVersionV2, + SchemaVersion: CurrentSchemaVersion, Release: "v0.2.6", Plugins: map[string]PluginRecord{ "future-agent": {Marketplace: "databricks-agent-skills", Plugin: "databricks", Scope: "user", Version: "0.2.6"}, @@ -748,7 +748,7 @@ func saveCopilotPlugin(t *testing.T) (context.Context, string) { dir, err := GlobalSkillsDir(ctx) require.NoError(t, err) require.NoError(t, SaveState(dir, &InstallState{ - SchemaVersion: schemaVersionV2, + SchemaVersion: CurrentSchemaVersion, Release: "v0.2.6", Plugins: map[string]PluginRecord{ agents.NameCopilot: {Marketplace: "databricks-agent-skills", Plugin: "databricks", Scope: "user", Version: "0.2.6"}, @@ -769,7 +769,7 @@ func TestUninstallSkillsWithResultUsesRecordedClaudeScope(t *testing.T) { dir, err := GlobalSkillsDir(ctx) require.NoError(t, err) require.NoError(t, SaveState(dir, &InstallState{ - SchemaVersion: schemaVersionV2, + SchemaVersion: CurrentSchemaVersion, Plugins: map[string]PluginRecord{ agents.NameClaudeCode: {Marketplace: "claude-plugins-official", Plugin: "databricks", Scope: scope}, }, diff --git a/libs/aitools/installer/state.go b/libs/aitools/installer/state.go index eba214eb79e..f44c33921d4 100644 --- a/libs/aitools/installer/state.go +++ b/libs/aitools/installer/state.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "fmt" + "io/fs" "os" "path/filepath" "strings" @@ -28,9 +29,10 @@ func clearFileRecords(files map[string]FileRecord, skillName string) { const stateFileName = ".state.json" -// schemaVersionV2 is the current on-disk state schema version. v2 adds the -// additive Plugins and Files maps; v1 state loads forward without data changes. -const schemaVersionV2 = 2 +// CurrentSchemaVersion is the on-disk state schema version this CLI writes. v2 +// added the Plugins and Files maps; v3 adds the optional MCP section. Older state +// loads forward without data changes. +const CurrentSchemaVersion = 3 // Scope constants for skill installation. const ( @@ -57,6 +59,37 @@ type InstallState struct { // e.g. "databricks/SKILL.md"). Added in schema v2; used to prune only the // skills we wrote that the user hasn't modified. Files map[string]FileRecord `json:"files,omitempty"` + // MCP records the Databricks MCP servers the `aitools mcp` commands wrote. + // Added in schema v3; omitted when none are recorded. SaveState ignores this + // field and keeps the section on disk; SaveMCPState is the only writer of it. + MCP *MCPState `json:"mcp,omitempty"` +} + +// MCPState is the MCP section of the install state: the servers this CLI added +// to agent configs, and how each one is bound to a Databricks profile. +type MCPState struct { + Servers []MCPEntry `json:"servers"` +} + +// MCPEntry is one installed MCP server: a service bound to one profile for one set of agents. +type MCPEntry struct { + Name string `json:"name"` + Service string `json:"service"` + Profile string `json:"profile"` + Host string `json:"host"` + WorkspaceID string `json:"workspace_id"` + SignInRequired bool `json:"sign_in_required"` + Command string `json:"command"` + ConfigFile string `json:"config_file"` + Agents map[string]MCPAgentRecord `json:"agents"` + InstalledAt time.Time `json:"installed_at"` + CLIVersion string `json:"cli_version"` +} + +// MCPAgentRecord is where an MCP entry was written for one agent. +type MCPAgentRecord struct { + Path string `json:"path"` + Scope string `json:"scope"` } // PluginRecord records a databricks plugin installed for an agent through the @@ -87,9 +120,44 @@ type FileRecord struct { Origin string `json:"origin,omitempty"` } +// hasInstallerRecords reports whether the state holds anything the installer writes: a release, +// skills, plugins, files or repo dirs. +func hasInstallerRecords(s *InstallState) bool { + return s.Release != "" || len(s.Skills) > 0 || len(s.Plugins) > 0 || len(s.Files) > 0 || len(s.RepoDirs) > 0 +} + +// isMCPOnly reports whether the state holds MCP records and nothing the installer wrote. The installer +// records a release in every state it saves, so such a file was written by the MCP commands alone. A file +// without an MCP section is never MCP-only, so a state the installer left behind, even an empty one, keeps +// the behavior it always had. +func (s *InstallState) isMCPOnly() bool { + return s != nil && s.MCP != nil && !hasInstallerRecords(s) +} + // LoadState reads install state from the given directory. -// Returns (nil, nil) when the state file does not exist. +// Returns (nil, nil) when the state file does not exist or holds only MCP records, since those are not +// an install of skills or plugins. LoadMCPState reads the MCP records. func LoadState(dir string) (*InstallState, error) { + state, err := readState(dir) + if err != nil || state.isMCPOnly() { + return nil, err + } + return state, nil +} + +// LoadMCPState reads the MCP section of the state file in the given directory. It returns nil when the +// file does not exist or has no MCP section. +func LoadMCPState(dir string) (*MCPState, error) { + state, err := readState(dir) + if err != nil || state == nil { + return nil, err + } + return state.MCP, nil +} + +// readState reads the state file in the given directory, whatever it holds. It returns (nil, nil) when +// the file does not exist. +func readState(dir string) (*InstallState, error) { path := filepath.Join(dir, stateFileName) data, err := os.ReadFile(path) if errors.Is(err, os.ErrNotExist) { @@ -108,18 +176,85 @@ func LoadState(dir string) (*InstallState, error) { } // migrateState brings a loaded state forward to the current schema version. It -// is forward-only and idempotent. v1 -> v2 needs no data transformation (the -// Plugins/Files maps are additive and optional), so it only stamps the version; -// writers lazily initialize the maps, matching how RepoDirs is handled. +// is forward-only and idempotent. The v1 -> v2 and v2 -> v3 steps need no data +// transformation (the Plugins, Files and MCP fields are additive and optional), +// so migration only stamps the version; writers lazily initialize the maps, +// matching how RepoDirs is handled. func migrateState(state *InstallState) { - if state.SchemaVersion < schemaVersionV2 { - state.SchemaVersion = schemaVersionV2 + if state.SchemaVersion < CurrentSchemaVersion { + state.SchemaVersion = CurrentSchemaVersion } } -// SaveState writes install state to the given directory atomically. -// Creates the directory if it does not exist. +// SaveState writes state to the given directory atomically, creating the directory if it does not +// exist. The MCP section is the one on disk: SaveState does not write the MCP field of state, so +// MCP records saved after state was loaded are kept. func SaveState(dir string, state *InstallState) error { + onDisk, err := readState(dir) + if err != nil { + return err + } + out := *state + out.MCP = nil + if onDisk != nil { + out.MCP = onDisk.MCP + } + return writeState(dir, &out) +} + +// SaveMCPState replaces the MCP section of the state file in the given directory with mcp. The skills +// and plugins records are kept as they are on disk. A nil or empty mcp removes the section, and the file +// is removed once it holds nothing else. +func SaveMCPState(dir string, mcp *MCPState) error { + st, err := readState(dir) + if err != nil { + return err + } + if st == nil { + if mcp == nil || len(mcp.Servers) == 0 { + return nil + } + st = &InstallState{ + SchemaVersion: CurrentSchemaVersion, + Skills: map[string]string{}, + RepoDirs: map[string]string{}, + Files: map[string]FileRecord{}, + } + } + st.MCP = nil + if mcp != nil && len(mcp.Servers) > 0 { + st.MCP = mcp + } + if st.MCP == nil && !hasInstallerRecords(st) { + return removeStateFile(dir) + } + return writeState(dir, st) +} + +// removeState deletes the state file once uninstall has removed every skill and plugin. Uninstall does +// not own MCP records, so when servers remain the file is rewritten to hold only them. +func removeState(dir string) error { + st, err := readState(dir) + if err != nil { + return err + } + if st != nil && st.MCP != nil && len(st.MCP.Servers) > 0 { + return writeState(dir, &InstallState{SchemaVersion: CurrentSchemaVersion, MCP: st.MCP}) + } + return removeStateFile(dir) +} + +// removeStateFile deletes the state file in the given directory. A missing file is not an error. +func removeStateFile(dir string) error { + err := os.Remove(filepath.Join(dir, stateFileName)) + if err != nil && !errors.Is(err, fs.ErrNotExist) { + return fmt.Errorf("failed to remove state file: %w", err) + } + return nil +} + +// writeState writes state to the state file in the given directory atomically, as written. +func writeState(dir string, state *InstallState) error { data, err := json.MarshalIndent(state, "", " ") if err != nil { return fmt.Errorf("failed to marshal state: %w", err) diff --git a/libs/aitools/installer/state_test.go b/libs/aitools/installer/state_test.go index 4abee62d8cb..feeb59d81bd 100644 --- a/libs/aitools/installer/state_test.go +++ b/libs/aitools/installer/state_test.go @@ -23,7 +23,7 @@ func TestLoadStateNonexistentFile(t *testing.T) { func TestSaveAndLoadStateRoundtrip(t *testing.T) { dir := t.TempDir() original := &InstallState{ - SchemaVersion: schemaVersionV2, + SchemaVersion: CurrentSchemaVersion, Release: "v0.2.0", LastUpdated: time.Date(2026, 3, 22, 10, 0, 0, 0, time.UTC), Skills: map[string]string{ @@ -136,7 +136,7 @@ func TestLoadStateMigratesV1ToV2(t *testing.T) { loaded, err := LoadState(dir) require.NoError(t, err) - assert.Equal(t, schemaVersionV2, loaded.SchemaVersion) + assert.Equal(t, CurrentSchemaVersion, loaded.SchemaVersion) // Migration is additive: existing data is untouched and the new maps stay nil. assert.Equal(t, map[string]string{"databricks": "1.0.0"}, loaded.Skills) assert.Nil(t, loaded.Plugins) @@ -148,7 +148,7 @@ func TestMigrateStateIsIdempotent(t *testing.T) { // second migrateState is a no-op. state := &InstallState{SchemaVersion: 1, Skills: map[string]string{"databricks": "1.0.0"}} migrateState(state) - assert.Equal(t, schemaVersionV2, state.SchemaVersion) + assert.Equal(t, CurrentSchemaVersion, state.SchemaVersion) migrated := *state migrateState(state) @@ -158,7 +158,7 @@ func TestMigrateStateIsIdempotent(t *testing.T) { func TestSaveAndLoadStateWithPluginAndFileRecords(t *testing.T) { dir := t.TempDir() original := &InstallState{ - SchemaVersion: schemaVersionV2, + SchemaVersion: CurrentSchemaVersion, Release: "v0.2.6", LastUpdated: time.Date(2026, 6, 24, 0, 0, 0, 0, time.UTC), Skills: map[string]string{"databricks": "1.0.0"}, @@ -187,7 +187,7 @@ func TestSaveAndLoadStateWithPluginAndFileRecords(t *testing.T) { func TestSaveAndLoadStateWithOptionalFields(t *testing.T) { dir := t.TempDir() original := &InstallState{ - SchemaVersion: schemaVersionV2, + SchemaVersion: CurrentSchemaVersion, IncludeExperimental: true, Release: "v0.3.0", LastUpdated: time.Date(2026, 3, 22, 12, 30, 0, 0, time.UTC), @@ -209,3 +209,166 @@ func TestSaveAndLoadStateWithOptionalFields(t *testing.T) { require.NoError(t, err) assert.Equal(t, original, loaded) } + +func TestSaveAndLoadStateKeepsMCPSection(t *testing.T) { + dir := t.TempDir() + original := &MCPState{Servers: []MCPEntry{{ + Name: "github-logfood", + Service: "system.ai.github", + Profile: "logfood", + Host: "https://adb-123.test", + WorkspaceID: "123", + SignInRequired: true, + Command: "/usr/local/bin/databricks", + Agents: map[string]MCPAgentRecord{ + "claude-code": {Path: "/home/me/.claude.json", Scope: "user"}, + }, + InstalledAt: time.Date(2026, 11, 12, 10, 12, 0, 0, time.UTC), + CLIVersion: "0.300.0", + }}} + require.NoError(t, SaveMCPState(dir, original)) + + loaded, err := LoadMCPState(dir) + require.NoError(t, err) + assert.Equal(t, original, loaded) +} + +// TestSaveStateKeepsMCPRecordsSavedAfterLoad checks that an installer save writes the MCP section +// on disk, not the copy loaded before an MCP save was made. +func TestSaveStateKeepsMCPRecordsSavedAfterLoad(t *testing.T) { + dir := t.TempDir() + require.NoError(t, SaveState(dir, &InstallState{SchemaVersion: CurrentSchemaVersion, Skills: map[string]string{"databricks": "1.0.0"}})) + + stale, err := LoadState(dir) + require.NoError(t, err) + require.NoError(t, SaveMCPState(dir, &MCPState{Servers: []MCPEntry{{Name: "github-logfood"}}})) + + stale.Skills["databricks"] = "1.1.0" + require.NoError(t, SaveState(dir, stale)) + + loaded, err := LoadState(dir) + require.NoError(t, err) + assert.Equal(t, map[string]string{"databricks": "1.1.0"}, loaded.Skills) + require.NotNil(t, loaded.MCP) + assert.Equal(t, []MCPEntry{{Name: "github-logfood"}}, loaded.MCP.Servers) +} + +// TestSaveMCPStateKeepsSkillRecords checks that an MCP save changes only the MCP section. +func TestSaveMCPStateKeepsSkillRecords(t *testing.T) { + dir := t.TempDir() + require.NoError(t, SaveState(dir, &InstallState{SchemaVersion: CurrentSchemaVersion, Skills: map[string]string{"databricks": "1.0.0"}})) + + require.NoError(t, SaveMCPState(dir, &MCPState{Servers: []MCPEntry{{Name: "github-logfood"}}})) + require.NoError(t, SaveMCPState(dir, &MCPState{})) + + loaded, err := LoadState(dir) + require.NoError(t, err) + assert.Equal(t, map[string]string{"databricks": "1.0.0"}, loaded.Skills) + assert.Nil(t, loaded.MCP) +} + +// TestSaveMCPStateRemovesFileWhenNothingLeft checks that the file goes once neither skills, plugins +// nor MCP servers remain, and that it is not created for an empty MCP section. +func TestSaveMCPStateRemovesFileWhenNothingLeft(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, stateFileName) + + require.NoError(t, SaveMCPState(dir, &MCPState{})) + _, err := os.Stat(path) + assert.ErrorIs(t, err, os.ErrNotExist) + + require.NoError(t, SaveMCPState(dir, &MCPState{Servers: []MCPEntry{{Name: "github-logfood"}}})) + require.NoError(t, SaveMCPState(dir, &MCPState{})) + _, err = os.Stat(path) + assert.ErrorIs(t, err, os.ErrNotExist) +} + +// TestSaveMCPStateKeepsInstallerLoadAsNoInstall checks that a file holding only MCP records loads as no +// install, so the installer treats it as it treats a missing file, and that a later skills write keeps +// the MCP records. +func TestSaveMCPStateKeepsInstallerLoadAsNoInstall(t *testing.T) { + dir := t.TempDir() + require.NoError(t, SaveMCPState(dir, &MCPState{Servers: []MCPEntry{{Name: "github-logfood"}}})) + + loaded, err := LoadState(dir) + require.NoError(t, err) + assert.Nil(t, loaded) + + require.NoError(t, SaveState(dir, &InstallState{SchemaVersion: CurrentSchemaVersion, Skills: map[string]string{"databricks": "1.0.0"}})) + mcp, err := LoadMCPState(dir) + require.NoError(t, err) + assert.Equal(t, []MCPEntry{{Name: "github-logfood"}}, mcp.Servers) +} + +// TestLoadStateHidesOnlyMCPOnlyFiles checks which files load as no install. A file with no MCP section +// loads as it always did, even when empty, since the installer wrote such files on main. Only a file +// holding MCP records and nothing the installer wrote loads as nil. +func TestLoadStateHidesOnlyMCPOnlyFiles(t *testing.T) { + mcp := &MCPState{Servers: []MCPEntry{{Name: "github-logfood"}}} + tests := []struct { + name string + state *InstallState + want bool + }{ + {name: "mcp only", state: &InstallState{MCP: mcp}}, + {name: "empty without mcp", state: &InstallState{SchemaVersion: 2}, want: true}, + {name: "release without skills, with mcp", state: &InstallState{Release: "v0.1.5", MCP: mcp}, want: true}, + {name: "files without skills", state: &InstallState{Files: map[string]FileRecord{"databricks/SKILL.md": {SHA256: "abc"}}}, want: true}, + {name: "repo dirs without skills", state: &InstallState{RepoDirs: map[string]string{"databricks": "skills"}}, want: true}, + {name: "skills", state: &InstallState{Skills: map[string]string{"databricks": "1.0.0"}, MCP: mcp}, want: true}, + {name: "plugins", state: &InstallState{Plugins: map[string]PluginRecord{"claude-code": {Plugin: "databricks"}}, MCP: mcp}, want: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + dir := t.TempDir() + require.NoError(t, writeState(dir, tt.state)) + + loaded, err := LoadState(dir) + require.NoError(t, err) + assert.Equal(t, tt.want, loaded != nil) + }) + } +} + +// TestSaveStateWritesEmptyState checks that SaveState writes the state it is given even when nothing +// is left in it, as the installer did before MCP records shared the file. +func TestSaveStateWritesEmptyState(t *testing.T) { + dir := t.TempDir() + require.NoError(t, SaveState(dir, &InstallState{SchemaVersion: CurrentSchemaVersion, Skills: map[string]string{"databricks": "1.0.0"}})) + + require.NoError(t, SaveState(dir, &InstallState{SchemaVersion: CurrentSchemaVersion})) + loaded, err := LoadState(dir) + require.NoError(t, err) + require.NotNil(t, loaded) + assert.Empty(t, loaded.Skills) +} + +// TestSaveStateKeepsMCPRecordsWhenNothingElseRemains checks that SaveState, once the skills are gone, +// keeps the MCP servers recorded on disk. +func TestSaveStateKeepsMCPRecordsWhenNothingElseRemains(t *testing.T) { + dir := t.TempDir() + require.NoError(t, SaveState(dir, &InstallState{SchemaVersion: CurrentSchemaVersion, Skills: map[string]string{"databricks": "1.0.0"}})) + require.NoError(t, SaveMCPState(dir, &MCPState{Servers: []MCPEntry{{Name: "github-logfood"}}})) + + require.NoError(t, SaveState(dir, &InstallState{SchemaVersion: CurrentSchemaVersion})) + mcp, err := LoadMCPState(dir) + require.NoError(t, err) + assert.Equal(t, []MCPEntry{{Name: "github-logfood"}}, mcp.Servers) +} + +func TestLoadStateMigratesV2ToV3AndSavesV3(t *testing.T) { + dir := t.TempDir() + v2 := `{"schema_version":2,"release":"v0.2.0","last_updated":"2026-03-22T10:00:00Z","skills":{"databricks":"1.0.0"}}` + require.NoError(t, os.WriteFile(filepath.Join(dir, stateFileName), []byte(v2), 0o644)) + + loaded, err := LoadState(dir) + require.NoError(t, err) + assert.Equal(t, 3, loaded.SchemaVersion) + assert.Nil(t, loaded.MCP) + + require.NoError(t, SaveState(dir, loaded)) + data, err := os.ReadFile(filepath.Join(dir, stateFileName)) + require.NoError(t, err) + assert.Contains(t, string(data), `"schema_version": 3`) + assert.NotContains(t, string(data), `"mcp"`) +} diff --git a/libs/aitools/installer/uninstall.go b/libs/aitools/installer/uninstall.go index 8f7cf1d2c10..ffa36c9b769 100644 --- a/libs/aitools/installer/uninstall.go +++ b/libs/aitools/installer/uninstall.go @@ -201,9 +201,8 @@ func UninstallSkillsWithResult(ctx context.Context, opts UninstallOptions) (*Uni // state file; otherwise persist the trimmed state. if len(state.Skills) == 0 && len(state.Plugins) == 0 { cleanOrphanedSymlinks(ctx, baseDir, scope, cwd) - stateFile := filepath.Join(baseDir, stateFileName) - if err := os.Remove(stateFile); err != nil && !errors.Is(err, fs.ErrNotExist) { - return nil, fmt.Errorf("failed to remove state file: %w", err) + if err := removeState(baseDir); err != nil { + return nil, err } } else { if err := SaveState(baseDir, state); err != nil { diff --git a/libs/aitools/installer/uninstall_test.go b/libs/aitools/installer/uninstall_test.go index b2f70d6501a..1413cde08c2 100644 --- a/libs/aitools/installer/uninstall_test.go +++ b/libs/aitools/installer/uninstall_test.go @@ -488,7 +488,7 @@ func TestUninstallCountsRemovedSkills(t *testing.T) { // so the skill counts as removed. globalDir := filepath.Join(tmp, ".databricks", "aitools", "skills") require.NoError(t, os.RemoveAll(filepath.Join(globalDir, "databricks-sql"))) - require.NoError(t, SaveState(globalDir, &InstallState{SchemaVersion: schemaVersionV2, Skills: map[string]string{"databricks-sql": "0.1.0"}})) + require.NoError(t, SaveState(globalDir, &InstallState{SchemaVersion: CurrentSchemaVersion, Skills: map[string]string{"databricks-sql": "0.1.0"}})) result, err = UninstallSkillsWithResult(ctx, UninstallOptions{}) require.NoError(t, err) assert.Equal(t, 1, result.SkillsChanged) @@ -574,7 +574,7 @@ func TestUninstallSkillFailuresAreSorted(t *testing.T) { require.NoError(t, os.MkdirAll(filepath.Join(globalDir, name), 0o755)) skills[name] = "0.1.0" } - require.NoError(t, SaveState(globalDir, &InstallState{SchemaVersion: schemaVersionV2, Skills: skills})) + require.NoError(t, SaveState(globalDir, &InstallState{SchemaVersion: CurrentSchemaVersion, Skills: skills})) orig := removeAllFn t.Cleanup(func() { removeAllFn = orig }) @@ -602,7 +602,7 @@ func TestUninstallTargetedUntrackedSkillGivesRecoveryGuidance(t *testing.T) { globalDir := filepath.Join(tmp, ".databricks", "aitools", "skills") require.NoError(t, SaveState(globalDir, &InstallState{ - SchemaVersion: schemaVersionV2, + SchemaVersion: CurrentSchemaVersion, Skills: map[string]string{"databricks-jobs": "0.1.0"}, })) @@ -612,3 +612,56 @@ func TestUninstallTargetedUntrackedSkillGivesRecoveryGuidance(t *testing.T) { assert.Contains(t, err.Error(), "Cursor") assert.Contains(t, err.Error(), "install --skills-only --agents cursor") } + +func TestUninstallKeepsStateFileWithMCPRecords(t *testing.T) { + tmp := setupTestHome(t) + globalDir := installTestSkills(t, tmp) + require.NoError(t, SaveMCPState(globalDir, &MCPState{Servers: []MCPEntry{{Name: "github-logfood"}}})) + + ctx := cmdio.MockDiscard(t.Context()) + _, err := UninstallSkillsWithResult(ctx, UninstallOptions{}) + require.NoError(t, err) + + // The skills are gone, but the MCP records stay in the file. + loaded, err := LoadState(globalDir) + require.NoError(t, err) + assert.Nil(t, loaded) + mcp, err := LoadMCPState(globalDir) + require.NoError(t, err) + assert.Equal(t, []MCPEntry{{Name: "github-logfood"}}, mcp.Servers) +} + +// TestUninstallMCPOnlyStateReturnsError checks that a state file holding only MCP records counts +// as having no skills or plugins, and that uninstall leaves the MCP records in place. +func TestUninstallMCPOnlyStateReturnsError(t *testing.T) { + tmp := setupTestHome(t) + globalDir := filepath.Join(tmp, ".databricks", "aitools", "skills") + require.NoError(t, SaveMCPState(globalDir, &MCPState{Servers: []MCPEntry{{Name: "github-logfood"}}})) + + _, err := UninstallSkillsWithResult(cmdio.MockDiscard(t.Context()), UninstallOptions{}) + require.Error(t, err) + assert.Contains(t, err.Error(), "no skills or plugins installed") + + mcp, err := LoadMCPState(globalDir) + require.NoError(t, err) + assert.Equal(t, []MCPEntry{{Name: "github-logfood"}}, mcp.Servers) +} + +// TestUninstallRemovesLeftoverFilesWithoutSkills checks that a state file with file and repo-dir +// records but no skills or plugins is still uninstalled, and the file is removed, as on main. +func TestUninstallRemovesLeftoverFilesWithoutSkills(t *testing.T) { + tmp := setupTestHome(t) + globalDir := filepath.Join(tmp, ".databricks", "aitools", "skills") + require.NoError(t, SaveState(globalDir, &InstallState{ + SchemaVersion: CurrentSchemaVersion, + Skills: map[string]string{}, + RepoDirs: map[string]string{"databricks-sql": "repo"}, + Files: map[string]FileRecord{"databricks-sql/SKILL.md": {SHA256: "abc"}}, + })) + + _, err := UninstallSkillsWithResult(cmdio.MockDiscard(t.Context()), UninstallOptions{}) + require.NoError(t, err) + + _, err = os.Stat(filepath.Join(globalDir, ".state.json")) + assert.ErrorIs(t, err, fs.ErrNotExist) +} diff --git a/libs/aitools/installer/update_test.go b/libs/aitools/installer/update_test.go index dad9840ce0a..18d2cc521b9 100644 --- a/libs/aitools/installer/update_test.go +++ b/libs/aitools/installer/update_test.go @@ -695,3 +695,41 @@ func TestFormatUpdateResultCheckMode(t *testing.T) { assert.Contains(t, checkOutput, "would add databricks-notebooks") assert.Contains(t, checkOutput, "Would update 2 skills.") } + +func TestUpdateMCPOnlyStateReturnsInstallHint(t *testing.T) { + tmp := setupTestHome(t) + ctx := cmdio.MockDiscard(t.Context()) + globalDir := filepath.Join(tmp, ".databricks", "aitools", "skills") + require.NoError(t, SaveMCPState(globalDir, &MCPState{Servers: []MCPEntry{{Name: "github-logfood"}}})) + + src := &mockManifestSource{manifest: testManifest()} + _, err := UpdateSkills(ctx, src, nil, UpdateOptions{}) + require.Error(t, err) + assert.Contains(t, err.Error(), "no skills or plugins installed") +} + +// TestUpdateAfterPruningEverySkillAddsNewSkills checks that an update which prunes every skill leaves +// a state file behind, so the next update adds the skills the manifest now lists. +func TestUpdateAfterPruningEverySkillAddsNewSkills(t *testing.T) { + tmp := setupTestHome(t) + ctx := cmdio.MockDiscard(t.Context()) + setupFetchMock(t) + t.Setenv("DATABRICKS_SKILLS_REF", testSkillsRef) + globalDir := filepath.Join(tmp, ".databricks", "aitools", "skills") + agent := testAgent(tmp) + + require.NoError(t, InstallSkillsForAgents(ctx, &mockManifestSource{manifest: testManifest()}, []*agents.Agent{agent}, InstallOptions{})) + t.Setenv("DATABRICKS_SKILLS_REF", "v0.2.0") + empty := &Manifest{Version: "1", UpdatedAt: "2024-02-01", Skills: map[string]SkillMeta{}} + _, err := UpdateSkills(ctx, &mockManifestSource{manifest: empty}, []*agents.Agent{agent}, UpdateOptions{}) + require.NoError(t, err) + + t.Setenv("DATABRICKS_SKILLS_REF", "v0.3.0") + _, err = UpdateSkills(ctx, &mockManifestSource{manifest: testManifest()}, []*agents.Agent{agent}, UpdateOptions{}) + require.NoError(t, err) + + state, err := LoadState(globalDir) + require.NoError(t, err) + require.NotNil(t, state) + assert.Contains(t, state.Skills, "databricks-sql") +} diff --git a/libs/aitools/mcp/agentconfig/writer.go b/libs/aitools/mcp/agentconfig/writer.go index b1b7ad26bce..6c0b27823c7 100644 --- a/libs/aitools/mcp/agentconfig/writer.go +++ b/libs/aitools/mcp/agentconfig/writer.go @@ -66,16 +66,11 @@ var launchKeys = []string{"command", "args", "env", "environment", "type"} // environment in OpenCode. var envKeys = []string{"env", "environment"} -// pinnedEnv is the environment variable that this CLI pins into an entry when it -// is set in the caller's environment. A write that does not pin it removes it from -// the entry. Other variables are the user's, and are kept. -const pinnedEnv = "DATABRICKS_CONFIG_FILE" - // ownedKeys returns the launch keys that the agent's builder writes. Upsert // updates these keys and keeps every other key of the entry. The probe passes a // variable, since a builder writes its env key only when it has variables. func ownedKeys(spec *mcpconfig.Spec) []string { - probe := spec.Entry("", nil, map[string]string{pinnedEnv: ""}) + probe := spec.Entry("", nil, map[string]string{mcpconfig.ConfigFileEnv: ""}) var keys []string for _, key := range launchKeys { if _, ok := probe[key]; ok { @@ -343,8 +338,8 @@ func keepUserKeys(current, want map[string]any, keys []string) (map[string]any, } // mergeEnv returns the env table after a write. It holds the variables of want, -// and the variables of have other than pinnedEnv. It reports false when the table -// is absent: want lacks it and no variable is left. +// and the variables of have other than the pinned config file variable. It +// reports false when the table is absent: want lacks it and no variable is left. func mergeEnv(have, want any, inWant bool) (any, bool, error) { haveEnv, err := envTable(have) if err != nil { @@ -353,7 +348,7 @@ func mergeEnv(have, want any, inWant bool) (any, bool, error) { wantEnv, _ := want.(map[string]any) out := map[string]any{} for k, v := range haveEnv { - if k != pinnedEnv { + if k != mcpconfig.ConfigFileEnv { out[k] = v } } diff --git a/libs/aitools/mcp/agentconfig/writer_test.go b/libs/aitools/mcp/agentconfig/writer_test.go index f0ab74fb6e2..4819ff495f7 100644 --- a/libs/aitools/mcp/agentconfig/writer_test.go +++ b/libs/aitools/mcp/agentconfig/writer_test.go @@ -562,12 +562,12 @@ func TestUpsertUpdateAddsAndRemovesLaunchKeys(t *testing.T) { writeFile(t, path, []byte(`{"mcpServers":{"`+testName+`":{"command":"`+testCmd+`","args":["aitools","mcp","serve","--agent","test"]}}}`), 0o600) a := testAgent(path, mcpconfig.FormatJSON, "mcpServers") - _, status, err := Upsert(t.Context(), a, testName, testCmd, testArgs("test"), map[string]string{pinnedEnv: "/cfg"}, false) + _, status, err := Upsert(t.Context(), a, testName, testCmd, testArgs("test"), map[string]string{mcpconfig.ConfigFileEnv: "/cfg"}, false) require.NoError(t, err) assert.Equal(t, StatusUpdated, status) entries, err := Read(t.Context(), a) require.NoError(t, err) - assert.Equal(t, map[string]any{pinnedEnv: "/cfg"}, entries[testName]["env"]) + assert.Equal(t, map[string]any{mcpconfig.ConfigFileEnv: "/cfg"}, entries[testName]["env"]) requireStrictJSON(t, string(readFile(t, path))) _, status, err = Upsert(t.Context(), a, testName, testCmd, testArgs("test"), nil, false) @@ -780,7 +780,7 @@ func TestUpsertRefusesEnvThatIsNotATable(t *testing.T) { writeFile(t, path, []byte(data), 0o600) a := testAgent(path, mcpconfig.FormatJSON, "mcpServers") - _, _, err := Upsert(t.Context(), a, testName, testCmd, testArgs("test"), map[string]string{pinnedEnv: "/cfg"}, false) + _, _, err := Upsert(t.Context(), a, testName, testCmd, testArgs("test"), map[string]string{mcpconfig.ConfigFileEnv: "/cfg"}, false) require.ErrorIs(t, err, ErrConfigInvalid) assert.Equal(t, data, string(readFile(t, path))) } diff --git a/libs/aitools/mcp/binding.go b/libs/aitools/mcp/binding.go new file mode 100644 index 00000000000..17320c755e3 --- /dev/null +++ b/libs/aitools/mcp/binding.go @@ -0,0 +1,230 @@ +package mcp + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "path/filepath" + + "github.com/databricks/cli/libs/aitools/mcpconfig" + "github.com/databricks/cli/libs/databrickscfg" + "github.com/databricks/cli/libs/env" + "github.com/databricks/cli/libs/shellquote" + "github.com/databricks/databricks-sdk-go/config" +) + +// bindExitCode is the exit status for binding failures, so callers can tell them apart +// from other errors. +const bindExitCode = 2 + +// Commands that binding messages tell the user to run. +const ( + authLoginCommand = "databricks auth login" + mcpRemoveCommand = "databricks aitools mcp remove" +) + +// BindCategory names the kind of a binding failure. The values are stable identifiers +// for the failure, not telemetry values. +type BindCategory string + +const ( + BindProfileNotFound BindCategory = "PROFILE_NOT_FOUND" + BindProfileHostChanged BindCategory = "PROFILE_HOST_CHANGED" + BindAuthFailed BindCategory = "AUTH_FAILED" + BindUncategorized BindCategory = "UNCATEGORIZED" +) + +// BindOptions selects what a proxy binds to. Service is the full name, for example system.ai.github. +type BindOptions struct { + Profile string + Service string + State *State + // Stderr receives the notice printed when no install record exists. It must not be nil. + Stderr io.Writer +} + +// BindError is a failed binding check. Its message is the text printed to stderr. +type BindError struct { + Category BindCategory + message string + cause error +} + +func (e *BindError) Error() string { + return e.message +} + +func (e *BindError) Unwrap() error { + return e.cause +} + +// ExitCode returns the process exit status for this failure. +func (e *BindError) ExitCode() int { + return bindExitCode +} + +// Bind checks that the profile still names the host and workspace recorded for the service, +// then authenticates with the profile's own credentials. It never reads stdin, prompts, or +// loads a bundle. It returns the resolved config and the matching state entry, which is nil +// when none exists. +// +// The config file is the one that DATABRICKS_CONFIG_FILE names in the context, resolved once: +// the profile lookup, the entry match and cfg.ConfigFile all use that path. The profile is +// checked before the SDK resolves the config, so a re-pointed host is never contacted. The CLI's +// token store reads DATABRICKS_CONFIG_FILE from the process environment instead, so a caller +// that sets the variable in the context must also set it in the process environment. +func Bind(ctx context.Context, opts BindOptions) (*config.Config, *Entry, error) { + configFile, err := resolveConfigFile(ctx, env.Get(ctx, mcpconfig.ConfigFileEnv)) + if err != nil { + return nil, nil, uncategorizedError(err) + } + ctx = env.Set(ctx, mcpconfig.ConfigFileEnv, configFile) + entry, err := findEntry(ctx, opts.State, opts.Service, opts.Profile, configFile) + if err != nil { + return nil, nil, err + } + name := opts.Service + if entry != nil { + name = entry.Name + } + + p, err := configFiles{}.profile(configFile, opts.Profile) + switch { + case errors.Is(err, errProfileMissing): + return nil, nil, profileGoneError(name, opts.Profile, filepath.ToSlash(configFile), entry, "no longer exists") + case errors.Is(err, errProfileNoHost): + return nil, nil, profileGoneError(name, opts.Profile, filepath.ToSlash(configFile), entry, "has no host") + case err != nil: + return nil, nil, uncategorizedError(err) + } + if entry != nil { + if drift := driftOf(*entry, p); drift != nil { + return nil, nil, driftError(name, opts.Profile, *entry, *drift) + } + } + + // The loaders take the profile's own settings and non-auth environment only. The + // profile loader chain in databrickscfg also fills missing credentials from the + // environment, but the proxy must not send a token meant for another workspace. + cfg := &config.Config{ + Profile: opts.Profile, + ConfigFile: configFile, + Loaders: []config.Loader{databrickscfg.ResolveNonAuthFromEnv, config.ConfigFile}, + } + if err := cfg.EnsureResolved(); err != nil { + // Configuration that the SDK rejects is not a credential failure, so a login would not fix it. + return nil, nil, uncategorizedError(err) + } + + if entry == nil { + fmt.Fprintf(opts.Stderr, "No install record for %s on profile \"%s\"; using its current host %s\n", opts.Service, opts.Profile, cfg.Host) + } + + // Authenticate only writes headers onto req, which is never sent. The request takes + // the command's context, as in cmd/root/auth.go. + req, err := http.NewRequestWithContext(ctx, http.MethodGet, "", nil) + if err != nil { + return nil, nil, uncategorizedError(err) + } + if err := cfg.Authenticate(req); err != nil { + return nil, nil, authError(opts.Profile, err) + } + return cfg, entry, nil +} + +// uncategorizedError wraps a failure that has no category of its own. Its message is the cause's. +func uncategorizedError(err error) error { + return &BindError{Category: BindUncategorized, message: err.Error(), cause: err} +} + +// removeCommand returns the command that removes the server bound to profileName. +func removeCommand(profileName string) string { + return mcpRemoveCommand + " --profile " + shellquote.BashArg(profileName) +} + +// profileGoneError builds the PROFILE_NOT_FOUND error for a profile that the config file does not +// name with a host, either because it is absent or because its section has no host. problem completes +// the sentence "which ... in ". Without a state entry the recorded host is unknown, so the +// recreate hint omits --host. An entry pinned to a config file puts that file in the recreate hint. +func profileGoneError(name, profileName, path string, entry *Entry, problem string) error { + recreate := authLoginCommand + " --profile " + shellquote.BashArg(profileName) + if entry != nil { + recreate = authLoginCommand + " --host " + shellquote.BashArg(entry.Host) + " --profile " + shellquote.BashArg(profileName) + if entry.ConfigFile != "" { + recreate = "DATABRICKS_CONFIG_FILE=" + shellquote.BashArg(path) + " " + recreate + } + } + message := fmt.Sprintf("MCP server %s is bound to Databricks profile \"%s\", which %s in %s. Recreate it with: %s or remove the server with: %s", + name, profileName, problem, path, recreate, removeCommand(profileName)) + return &BindError{Category: BindProfileNotFound, message: message} +} + +// driftError is the PROFILE_HOST_CHANGED error for an entry whose profile now names another host, +// or another workspace on the same host. +func driftError(name, profileName string, entry Entry, drift Drift) error { + recordedHost, recordedWorkspaceID := recordedTarget(entry) + var message string + if NormalizeHost(recordedHost) != NormalizeHost(drift.CurrentHost) { + message = fmt.Sprintf("MCP server %s was set up for %s, but profile \"%s\" now points at %s. Run: %s and add it again", + name, recordedHost, profileName, drift.CurrentHost, removeCommand(profileName)) + } else { + message = fmt.Sprintf("MCP server %s was set up for workspace %s, but profile \"%s\" now points at workspace %s. Run: %s and add it again", + name, recordedWorkspaceID, profileName, drift.CurrentWorkspaceID, removeCommand(profileName)) + } + return &BindError{Category: BindProfileHostChanged, message: message} +} + +// configFileError is the PROFILE_HOST_CHANGED error for an entry whose config file is not the one in +// use. The profile may name the same host there, but the server was set up against the recorded file. +func configFileError(name, profileName, recordedPath, currentPath string) error { + message := fmt.Sprintf("MCP server %s was set up with config file %s, but profile \"%s\" is read from %s now. Run: %s and add it again, or set DATABRICKS_CONFIG_FILE to %s", + name, recordedPath, profileName, currentPath, removeCommand(profileName), shellquote.BashArg(recordedPath)) + return &BindError{Category: BindProfileHostChanged, message: message} +} + +// authError is the AUTH_FAILED error for a credential that the profile's own settings could not +// provide. The message points at the login command for the profile. +func authError(profileName string, cause error) error { + message := fmt.Sprintf("%s\nRun: %s --profile %s", cause, authLoginCommand, shellquote.BashArg(profileName)) + return &BindError{Category: BindAuthFailed, message: message, cause: cause} +} + +// findEntry returns the entry for the service and profile whose config file is configFile, or nil when +// the service and profile have no entry at all. Both sides are compared as resolved paths, so an entry +// with no pinned file matches the default file. +// +// An entry for the service and profile in another file is an error, not a missing entry: the server was +// set up against that file, and binding through this one would switch it without a record. An entry +// whose file cannot be resolved, such as a "~" path with no home directory, cannot be compared. The +// bind fails on it, since it might be the match. +func findEntry(ctx context.Context, state *State, service, profileName, configFile string) (*Entry, error) { + var unresolved error + var other *Entry + var otherPath string + for i := range state.Servers { + entry := &state.Servers[i] + if entry.Service != service || entry.Profile != profileName { + continue + } + path, err := resolveConfigFile(ctx, entry.ConfigFile) + if err != nil { + unresolved = errors.Join(unresolved, fmt.Errorf("MCP server %s: %w", entry.Name, err)) + continue + } + if samePath(path, configFile) { + return entry, nil + } + if other == nil { + other, otherPath = entry, path + } + } + if unresolved != nil { + return nil, uncategorizedError(unresolved) + } + if other != nil { + return nil, configFileError(other.Name, profileName, filepath.ToSlash(otherPath), filepath.ToSlash(configFile)) + } + return nil, nil +} diff --git a/libs/aitools/mcp/binding_test.go b/libs/aitools/mcp/binding_test.go new file mode 100644 index 00000000000..7e0220c0165 --- /dev/null +++ b/libs/aitools/mcp/binding_test.go @@ -0,0 +1,782 @@ +package mcp_test + +import ( + "bytes" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + + "github.com/databricks/cli/libs/aitools/mcp" + "github.com/databricks/cli/libs/env" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const ( + bindingTestService = "system.ai.github" + bindingTestProfile = "logfood" + bindingTestHost = "https://adb-123.test" + bindingTestToken = "dapi-profile-token" +) + +// bindingTestWriteConfig writes a .databrickscfg with contents and returns its path. +func bindingTestWriteConfig(t *testing.T, contents string) string { + t.Helper() + path := filepath.Join(t.TempDir(), ".databrickscfg") + require.NoError(t, os.WriteFile(path, []byte(contents), 0o600)) + return path +} + +// bindingTestConfig writes a .databrickscfg, points DATABRICKS_CONFIG_FILE at it, and sets +// steering variables that name another workspace. Bind must ignore those. The home directory +// is a separate temp dir so the config path is never abbreviated to "~" in messages. +func bindingTestConfig(t *testing.T, contents string) string { + t.Helper() + path := bindingTestWriteConfig(t, contents) + t.Setenv(env.HomeEnvVar(), t.TempDir()) + t.Setenv("DATABRICKS_CONFIG_FILE", path) + t.Setenv("DATABRICKS_HOST", "https://adb-999.test") + t.Setenv("DATABRICKS_TOKEN", "dapi-env-token") + t.Setenv("DATABRICKS_CONFIG_PROFILE", "other") + t.Setenv("DATABRICKS_AUTH_TYPE", "basic") + return path +} + +func bindingTestProfileContents(token string) string { + return fmt.Sprintf(`[%s] +host = %s +auth_type = pat +token = %s +`, bindingTestProfile, bindingTestHost, token) +} + +// bindingTestState returns a state with one entry pinned to configFile, the file the test wrote. +func bindingTestState(configFile, host string) *mcp.State { + return &mcp.State{Servers: []mcp.Entry{{ + Name: "github-logfood", + Service: bindingTestService, + Profile: bindingTestProfile, + Host: host, + ConfigFile: configFile, + }}} +} + +func TestBindSucceedsWithStateEntry(t *testing.T) { + cfgPath := bindingTestConfig(t, bindingTestProfileContents(bindingTestToken)) + stderr := &bytes.Buffer{} + + cfg, entry, err := mcp.Bind(t.Context(), mcp.BindOptions{ + Profile: bindingTestProfile, + Service: bindingTestService, + State: bindingTestState(cfgPath, bindingTestHost), + Stderr: stderr, + }) + require.NoError(t, err) + assert.Equal(t, bindingTestProfile, cfg.Profile) + assert.Equal(t, bindingTestHost, cfg.Host) + assert.Equal(t, bindingTestToken, cfg.Token) + require.NotNil(t, entry) + assert.Equal(t, "github-logfood", entry.Name) + assert.Empty(t, stderr.String()) +} + +func TestBindPrintsNoticeWithoutStateEntry(t *testing.T) { + bindingTestConfig(t, bindingTestProfileContents(bindingTestToken)) + stderr := &bytes.Buffer{} + + cfg, entry, err := mcp.Bind(t.Context(), mcp.BindOptions{ + Profile: bindingTestProfile, + Service: bindingTestService, + State: &mcp.State{}, + Stderr: stderr, + }) + require.NoError(t, err) + assert.Nil(t, entry) + assert.Equal(t, bindingTestHost, cfg.Host) + assert.Equal(t, "No install record for system.ai.github on profile \"logfood\"; using its current host https://adb-123.test\n", stderr.String()) +} + +// bindingTestResolved returns path with its symlinks resolved, which is how Bind names an existing +// config file. Temp directories are symlinks on some systems, for example macOS. +func bindingTestResolved(t *testing.T, path string) string { + t.Helper() + resolved, err := filepath.EvalSymlinks(path) + require.NoError(t, err) + return resolved +} + +func TestBindProfileAbsent(t *testing.T) { + path := bindingTestResolved(t, bindingTestConfig(t, bindingTestProfileContents(bindingTestToken))) + + tests := []struct { + name string + state *mcp.State + want string + }{ + { + name: "with state entry", + state: &mcp.State{Servers: []mcp.Entry{{ + Name: "github-gone", + Service: bindingTestService, + Profile: "gone", + Host: bindingTestHost, + ConfigFile: path, + }}}, + want: fmt.Sprintf(`MCP server github-gone is bound to Databricks profile "gone", which no longer exists in %s. Recreate it with: DATABRICKS_CONFIG_FILE=%s databricks auth login --host https://adb-123.test --profile gone or remove the server with: databricks aitools mcp remove --profile gone`, filepath.ToSlash(path), filepath.ToSlash(path)), + }, + { + name: "without state entry", + state: &mcp.State{}, + want: fmt.Sprintf(`MCP server system.ai.github is bound to Databricks profile "gone", which no longer exists in %s. Recreate it with: databricks auth login --profile gone or remove the server with: databricks aitools mcp remove --profile gone`, filepath.ToSlash(path)), + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, _, err := mcp.Bind(t.Context(), mcp.BindOptions{ + Profile: "gone", + Service: bindingTestService, + State: tt.state, + Stderr: &bytes.Buffer{}, + }) + requireBindError(t, err, mcp.BindProfileNotFound) + assert.Equal(t, tt.want, err.Error()) + }) + } +} + +// TestBindConfigFileAbsent checks that an entry pinned to a config file that no longer exists reports +// the profile as gone from that file. +func TestBindConfigFileAbsent(t *testing.T) { + bindingTestConfig(t, bindingTestProfileContents(bindingTestToken)) + path := filepath.Join(t.TempDir(), "absent") + t.Setenv("DATABRICKS_CONFIG_FILE", path) + + _, _, err := mcp.Bind(t.Context(), mcp.BindOptions{ + Profile: bindingTestProfile, + Service: bindingTestService, + State: bindingTestState(path, bindingTestHost), + Stderr: &bytes.Buffer{}, + }) + requireBindError(t, err, mcp.BindProfileNotFound) + assert.Contains(t, err.Error(), "which no longer exists in "+filepath.ToSlash(path)+". Recreate") +} + +func TestBindHostChanged(t *testing.T) { + tests := []struct { + name string + entry string + want string + }{ + { + name: "host", + entry: "https://adb-999.test", + want: "MCP server github-logfood was set up for https://adb-999.test, but profile \"logfood\" now points at https://adb-123.test. Run: databricks aitools mcp remove --profile logfood and add it again", + }, + { + name: "host with a query naming another workspace on the same host", + entry: "https://adb-999.test/?o=111", + want: "MCP server github-logfood was set up for https://adb-999.test, but profile \"logfood\" now points at https://adb-123.test. Run: databricks aitools mcp remove --profile logfood and add it again", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cfgPath := bindingTestConfig(t, bindingTestProfileContents(bindingTestToken)) + + _, _, err := mcp.Bind(t.Context(), mcp.BindOptions{ + Profile: bindingTestProfile, + Service: bindingTestService, + State: bindingTestState(cfgPath, tt.entry), + Stderr: &bytes.Buffer{}, + }) + requireBindError(t, err, mcp.BindProfileHostChanged) + assert.Equal(t, tt.want, err.Error()) + }) + } +} + +// TestBindHostChangedDoesNotContactNewHost checks that a re-pointed profile is rejected before +// any request reaches the new host. +func TestBindHostChangedDoesNotContactNewHost(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t.Errorf("unexpected request to the re-pointed host: %s %s", r.Method, r.URL) + w.WriteHeader(http.StatusInternalServerError) + })) + t.Cleanup(server.Close) + cfgPath := bindingTestConfig(t, fmt.Sprintf("[%s]\nhost = %s\nauth_type = pat\ntoken = %s\n", bindingTestProfile, server.URL, bindingTestToken)) + + _, _, err := mcp.Bind(t.Context(), mcp.BindOptions{ + Profile: bindingTestProfile, + Service: bindingTestService, + State: bindingTestState(cfgPath, bindingTestHost), + Stderr: &bytes.Buffer{}, + }) + requireBindError(t, err, mcp.BindProfileHostChanged) +} + +func TestBindWorkspaceChanged(t *testing.T) { + const want = "MCP server github-logfood was set up for workspace 111, but profile \"logfood\" now points at workspace 222. Run: databricks aitools mcp remove --profile logfood and add it again" + tests := []struct { + name string + entryHost string + entryWS string + profileLine string + }{ + { + name: "workspace_id in the profile", + entryHost: bindingTestHost, + entryWS: "111", + profileLine: "workspace_id = 222\n", + }, + { + name: "workspace in the recorded host query", + entryHost: bindingTestHost + "/?o=111", + profileLine: "workspace_id = 222\n", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cfgPath := bindingTestConfig(t, fmt.Sprintf("[%s]\nhost = %s\n%sauth_type = pat\ntoken = %s\n", bindingTestProfile, bindingTestHost, tt.profileLine, bindingTestToken)) + state := bindingTestState(cfgPath, tt.entryHost) + state.Servers[0].WorkspaceID = tt.entryWS + + _, _, err := mcp.Bind(t.Context(), mcp.BindOptions{ + Profile: bindingTestProfile, + Service: bindingTestService, + State: state, + Stderr: &bytes.Buffer{}, + }) + requireBindError(t, err, mcp.BindProfileHostChanged) + assert.Equal(t, want, err.Error()) + }) + } +} + +func TestBindWorkspaceNotComparedWhenProfileNamesNone(t *testing.T) { + cfgPath := bindingTestConfig(t, fmt.Sprintf("[%s]\nhost = %s\nworkspace_id = none\nauth_type = pat\ntoken = %s\n", bindingTestProfile, bindingTestHost, bindingTestToken)) + state := bindingTestState(cfgPath, bindingTestHost) + state.Servers[0].WorkspaceID = "111" + + _, entry, err := mcp.Bind(t.Context(), mcp.BindOptions{ + Profile: bindingTestProfile, + Service: bindingTestService, + State: state, + Stderr: &bytes.Buffer{}, + }) + require.NoError(t, err) + assert.NotNil(t, entry) +} + +func TestBindHostUnchangedWhenOnlyTrailingSlashDiffers(t *testing.T) { + cfgPath := bindingTestConfig(t, bindingTestProfileContents(bindingTestToken)) + + _, entry, err := mcp.Bind(t.Context(), mcp.BindOptions{ + Profile: bindingTestProfile, + Service: bindingTestService, + State: bindingTestState(cfgPath, "https://adb-123.test/"), + Stderr: &bytes.Buffer{}, + }) + require.NoError(t, err) + assert.NotNil(t, entry) +} + +// TestBindNeverUsesEnvTokenForProfileWithoutToken checks that a profile without a token does not +// pick up DATABRICKS_TOKEN from the environment, which names another workspace here. +func TestBindNeverUsesEnvTokenForProfileWithoutToken(t *testing.T) { + cfgPath := bindingTestConfig(t, bindingTestProfileContents("")) + + _, _, err := mcp.Bind(t.Context(), mcp.BindOptions{ + Profile: bindingTestProfile, + Service: bindingTestService, + State: bindingTestState(cfgPath, bindingTestHost), + Stderr: &bytes.Buffer{}, + }) + requireBindError(t, err, mcp.BindAuthFailed) + assert.Contains(t, err.Error(), "\nRun: databricks auth login --profile logfood") + assert.NotContains(t, err.Error(), "dapi-env-token") + assert.Error(t, errors.Unwrap(err)) +} + +// TestBindReadsConfigFileFromContext checks that the config file named in the context, not the +// process environment, is used for both the profile lookup and authentication. +func TestBindReadsConfigFileFromContext(t *testing.T) { + bindingTestConfig(t, bindingTestProfileContents(bindingTestToken)) + path := bindingTestWriteConfig(t, bindingTestProfileContents(bindingTestToken)) + t.Setenv("DATABRICKS_CONFIG_FILE", filepath.Join(t.TempDir(), "absent")) + ctx := env.Set(t.Context(), "DATABRICKS_CONFIG_FILE", path) + + cfg, _, err := mcp.Bind(ctx, mcp.BindOptions{ + Profile: bindingTestProfile, + Service: bindingTestService, + State: bindingTestState(path, bindingTestHost), + Stderr: &bytes.Buffer{}, + }) + require.NoError(t, err) + assert.Equal(t, bindingTestToken, cfg.Token) +} + +// TestBindMatchesEntryByConfigFile checks that an entry pinned to another config file does not +// bind a profile of the same name in the current file. +func TestBindMatchesEntryByConfigFile(t *testing.T) { + bindingTestConfig(t, bindingTestProfileContents(bindingTestToken)) + current := bindingTestWriteConfig(t, "[logfood]\nhost = https://adb-456.test\nauth_type = pat\ntoken = dapi-current\n") + ctx := env.Set(t.Context(), "DATABRICKS_CONFIG_FILE", current) + state := &mcp.State{Servers: []mcp.Entry{ + {Name: "other", Service: bindingTestService, Profile: bindingTestProfile, Host: bindingTestHost, ConfigFile: "/elsewhere/.databrickscfg"}, + {Name: "current", Service: bindingTestService, Profile: bindingTestProfile, Host: "https://adb-456.test", ConfigFile: current}, + }} + + cfg, entry, err := mcp.Bind(ctx, mcp.BindOptions{ + Profile: bindingTestProfile, + Service: bindingTestService, + State: state, + Stderr: &bytes.Buffer{}, + }) + require.NoError(t, err) + require.NotNil(t, entry) + assert.Equal(t, "current", entry.Name) + assert.Equal(t, "dapi-current", cfg.Token) +} + +func TestBindTokenCannotBeMinted(t *testing.T) { + cfgPath := bindingTestConfig(t, bindingTestProfileContents("")) + t.Setenv("DATABRICKS_TOKEN", "") + + _, _, err := mcp.Bind(t.Context(), mcp.BindOptions{ + Profile: bindingTestProfile, + Service: bindingTestService, + State: bindingTestState(cfgPath, bindingTestHost), + Stderr: &bytes.Buffer{}, + }) + requireBindError(t, err, mcp.BindAuthFailed) + assert.Contains(t, err.Error(), "\nRun: databricks auth login --profile logfood") + assert.Error(t, errors.Unwrap(err)) +} + +// TestBindDoesNotReadStdin feeds a message on stdin and checks Bind leaves it unread. +func TestBindDoesNotReadStdin(t *testing.T) { + cfgPath := bindingTestConfig(t, bindingTestProfileContents(bindingTestToken)) + r, w, err := os.Pipe() + require.NoError(t, err) + t.Cleanup(func() { _ = r.Close() }) + const message = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\"}\n" + _, err = w.WriteString(message) + require.NoError(t, err) + require.NoError(t, w.Close()) + stdin := os.Stdin + os.Stdin = r + t.Cleanup(func() { os.Stdin = stdin }) + + _, _, err = mcp.Bind(t.Context(), mcp.BindOptions{ + Profile: bindingTestProfile, + Service: bindingTestService, + State: bindingTestState(cfgPath, bindingTestHost), + Stderr: &bytes.Buffer{}, + }) + require.NoError(t, err) + + rest, err := io.ReadAll(r) + require.NoError(t, err) + assert.Equal(t, message, string(rest)) +} + +func requireBindError(t *testing.T, err error, want mcp.BindCategory) { + t.Helper() + require.Error(t, err) + var bindErr *mcp.BindError + require.ErrorAs(t, err, &bindErr) + assert.Equal(t, want, bindErr.Category) + assert.Equal(t, 2, bindErr.ExitCode()) +} + +// bindingTestDefaultConfig writes contents to ~/.databrickscfg in a fresh home directory, with +// DATABRICKS_CONFIG_FILE empty, and returns the path of the default file. +func bindingTestDefaultConfig(t *testing.T, contents string) string { + t.Helper() + home := t.TempDir() + t.Setenv(env.HomeEnvVar(), home) + t.Setenv("DATABRICKS_CONFIG_FILE", "") + t.Setenv("DATABRICKS_HOST", "https://adb-999.test") + t.Setenv("DATABRICKS_TOKEN", "dapi-env-token") + path := filepath.Join(home, ".databrickscfg") + require.NoError(t, os.WriteFile(path, []byte(contents), 0o600)) + return path +} + +// TestBindWorkspaceFromHostQueryChanged checks that a workspace named in the profile's host query +// is compared with the recorded one, as the SDK resolves it. +func TestBindWorkspaceFromHostQueryChanged(t *testing.T) { + for _, query := range []string{"?o=222", "?w=222", "?workspace_id=222"} { + t.Run(query, func(t *testing.T) { + cfgPath := bindingTestConfig(t, fmt.Sprintf("[%s]\nhost = %s/%s\nauth_type = pat\ntoken = %s\n", bindingTestProfile, bindingTestHost, query, bindingTestToken)) + state := bindingTestState(cfgPath, bindingTestHost) + state.Servers[0].WorkspaceID = "111" + + _, _, err := mcp.Bind(t.Context(), mcp.BindOptions{ + Profile: bindingTestProfile, + Service: bindingTestService, + State: state, + Stderr: &bytes.Buffer{}, + }) + requireBindError(t, err, mcp.BindProfileHostChanged) + assert.Equal(t, "MCP server github-logfood was set up for workspace 111, but profile \"logfood\" now points at workspace 222. Run: databricks aitools mcp remove --profile logfood and add it again", err.Error()) + }) + } +} + +// TestBindWorkspaceFromHostQueryNoneIsUnset checks that a host query naming no workspace is not +// compared. +func TestBindWorkspaceFromHostQueryNoneIsUnset(t *testing.T) { + for _, query := range []string{"?o=none", "?w=none"} { + t.Run(query, func(t *testing.T) { + cfgPath := bindingTestConfig(t, fmt.Sprintf("[%s]\nhost = %s/%s\nauth_type = pat\ntoken = %s\n", bindingTestProfile, bindingTestHost, query, bindingTestToken)) + state := bindingTestState(cfgPath, bindingTestHost) + state.Servers[0].WorkspaceID = "111" + + _, entry, err := mcp.Bind(t.Context(), mcp.BindOptions{ + Profile: bindingTestProfile, + Service: bindingTestService, + State: state, + Stderr: &bytes.Buffer{}, + }) + require.NoError(t, err) + assert.NotNil(t, entry) + }) + } +} + +// TestBindUnpinnedEntryMatchesDefaultConfigFile checks that an entry with no pinned config file +// names the default file, so it matches whether DATABRICKS_CONFIG_FILE is unset or names that file. +func TestBindUnpinnedEntryMatchesDefaultConfigFile(t *testing.T) { + defaultPath := bindingTestDefaultConfig(t, bindingTestProfileContents(bindingTestToken)) + state := &mcp.State{Servers: []mcp.Entry{{ + Name: "github-logfood", + Service: bindingTestService, + Profile: bindingTestProfile, + Host: "https://adb-999.test", + }}} + + for _, configFile := range []string{"", defaultPath} { + t.Run("env="+configFile, func(t *testing.T) { + t.Setenv("DATABRICKS_CONFIG_FILE", configFile) + + _, _, err := mcp.Bind(t.Context(), mcp.BindOptions{ + Profile: bindingTestProfile, + Service: bindingTestService, + State: state, + Stderr: &bytes.Buffer{}, + }) + requireBindError(t, err, mcp.BindProfileHostChanged) + }) + } +} + +// TestBindUnpinnedEntryDoesNotMatchOtherConfigFile checks that an entry with no pinned config file +// does not bind a profile of the same name in another config file. +// TestBindUnpinnedEntryFailsForOtherConfigFile checks that an unpinned entry, which names the default +// file, stops a bind through another file. The profile there points at another host, and the bind must +// not switch the server to it silently. +func TestBindUnpinnedEntryFailsForOtherConfigFile(t *testing.T) { + defaultPath := bindingTestDefaultConfig(t, bindingTestProfileContents(bindingTestToken)) + other := bindingTestWriteConfig(t, "[logfood]\nhost = https://adb-456.test\nauth_type = pat\ntoken = dapi-other\n") + t.Setenv("DATABRICKS_CONFIG_FILE", other) + stderr := &bytes.Buffer{} + + _, _, err := mcp.Bind(t.Context(), mcp.BindOptions{ + Profile: bindingTestProfile, + Service: bindingTestService, + State: bindingTestState("", bindingTestHost), + Stderr: stderr, + }) + requireBindError(t, err, mcp.BindProfileHostChanged) + assert.Contains(t, err.Error(), "was set up with config file "+filepath.ToSlash(bindingTestResolved(t, defaultPath))) + assert.Empty(t, stderr.String()) +} + +// TestBindWithoutHomeAndAbsoluteConfigFile checks that a bind needs no home directory when the +// config file is named by an absolute path. +func TestBindWithoutHomeAndAbsoluteConfigFile(t *testing.T) { + cfgPath := bindingTestConfig(t, bindingTestProfileContents(bindingTestToken)) + t.Setenv(env.HomeEnvVar(), "") + + cfg, entry, err := mcp.Bind(t.Context(), mcp.BindOptions{ + Profile: bindingTestProfile, + Service: bindingTestService, + State: bindingTestState(cfgPath, bindingTestHost), + Stderr: &bytes.Buffer{}, + }) + require.NoError(t, err) + assert.NotNil(t, entry) + assert.Equal(t, bindingTestToken, cfg.Token) +} + +// TestBindWorkspaceFollowsSDKResolution checks that the workspace a profile names is the one the SDK +// resolves: workspace_id first, then the ?w= query, then a numeric ?o= or ?workspace_id=. A workspace +// named "none" is not compared. +func TestBindWorkspaceFollowsSDKResolution(t *testing.T) { + tests := []struct { + name string + workspaceID string // the profile's workspace_id, "" when it has none + query string // the host query, with its leading "?" + recorded string + // wantWorkspace is the workspace the drift names. It is "" when no drift is expected. + wantWorkspace string + }{ + {name: "w wins over o", query: "?o=111&w=222", recorded: "111", wantWorkspace: "222"}, + {name: "w wins over o when recorded", query: "?o=111&w=222", recorded: "222"}, + {name: "non-numeric o is ignored when w names", query: "?o=abc&w=222", recorded: "222"}, + {name: "non-numeric o names none", query: "?o=abc", recorded: "111"}, + {name: "workspace_id wins over the query", workspaceID: "333", query: "?o=222", recorded: "222", wantWorkspace: "333"}, + {name: "workspace_id wins when recorded", workspaceID: "333", query: "?o=222", recorded: "333"}, + {name: "none in workspace_id names none", workspaceID: "none", query: "?o=222", recorded: "111"}, + {name: "none in o names none", query: "?o=none", recorded: "111"}, + {name: "none in w names none", query: "?w=none", recorded: "111"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + contents := fmt.Sprintf("[%s]\nhost = %s/%s\n", bindingTestProfile, bindingTestHost, tt.query) + if tt.workspaceID != "" { + contents += "workspace_id = " + tt.workspaceID + "\n" + } + contents += "auth_type = pat\ntoken = " + bindingTestToken + "\n" + cfgPath := bindingTestConfig(t, contents) + state := bindingTestState(cfgPath, bindingTestHost) + state.Servers[0].WorkspaceID = tt.recorded + + _, entry, err := mcp.Bind(t.Context(), mcp.BindOptions{ + Profile: bindingTestProfile, + Service: bindingTestService, + State: state, + Stderr: &bytes.Buffer{}, + }) + if tt.wantWorkspace == "" { + require.NoError(t, err) + assert.NotNil(t, entry) + return + } + requireBindError(t, err, mcp.BindProfileHostChanged) + assert.Contains(t, err.Error(), "now points at workspace "+tt.wantWorkspace+".") + }) + } +} + +// TestBindMatchesEntryWhenHomeIsSymlink checks that an entry pinned as "~/..." matches the config file +// named by its real path when HOME is a symlink to the directory that holds the file. +func TestBindMatchesEntryWhenHomeIsSymlink(t *testing.T) { + cfgPath := bindingTestConfig(t, bindingTestProfileContents(bindingTestToken)) + link := filepath.Join(t.TempDir(), "home") + if err := os.Symlink(filepath.Dir(cfgPath), link); err != nil { + t.Skipf("cannot create symlink: %v", err) + } + t.Setenv(env.HomeEnvVar(), link) + + _, entry, err := mcp.Bind(t.Context(), mcp.BindOptions{ + Profile: bindingTestProfile, + Service: bindingTestService, + State: bindingTestState("~/.databrickscfg", bindingTestHost), + Stderr: &bytes.Buffer{}, + }) + require.NoError(t, err) + assert.NotNil(t, entry) +} + +// TestBindMatchesEntryWhenDotDotFollowsSymlink checks that a config path with ".." after a symlink names +// the file the OS reads through the link's target, which is also the entry's resolved path. +func TestBindMatchesEntryWhenDotDotFollowsSymlink(t *testing.T) { + bindingTestConfig(t, bindingTestProfileContents(bindingTestToken)) + base := t.TempDir() + cfgPath := filepath.Join(base, "a", ".databrickscfg") + require.NoError(t, os.MkdirAll(filepath.Join(base, "a", "b"), 0o755)) + require.NoError(t, os.WriteFile(cfgPath, []byte(bindingTestProfileContents(bindingTestToken)), 0o600)) + link := filepath.Join(base, "link") + if err := os.Symlink(filepath.Join(base, "a", "b"), link); err != nil { + t.Skipf("cannot create symlink: %v", err) + } + // filepath.Join would clean the ".." away, so the path is joined by hand. + sep := string(filepath.Separator) + t.Setenv("DATABRICKS_CONFIG_FILE", link+sep+".."+sep+".databrickscfg") + + _, entry, err := mcp.Bind(t.Context(), mcp.BindOptions{ + Profile: bindingTestProfile, + Service: bindingTestService, + State: bindingTestState(bindingTestResolved(t, cfgPath), bindingTestHost), + Stderr: &bytes.Buffer{}, + }) + require.NoError(t, err) + assert.NotNil(t, entry) +} + +// TestBindSkipsEntryWithoutHomeWhenAbsoluteEntryMatches checks that an entry whose "~" path cannot be +// resolved, because HOME is unset, does not stop the match against an entry with an absolute path. +func TestBindSkipsEntryWithoutHomeWhenAbsoluteEntryMatches(t *testing.T) { + cfgPath := bindingTestConfig(t, bindingTestProfileContents(bindingTestToken)) + t.Setenv(env.HomeEnvVar(), "") + state := &mcp.State{Servers: []mcp.Entry{ + {Name: "github-home", Service: bindingTestService, Profile: bindingTestProfile, Host: "https://adb-999.test", ConfigFile: "~/.databrickscfg"}, + {Name: "github-absolute", Service: bindingTestService, Profile: bindingTestProfile, Host: bindingTestHost, ConfigFile: cfgPath}, + }} + + _, entry, err := mcp.Bind(t.Context(), mcp.BindOptions{ + Profile: bindingTestProfile, + Service: bindingTestService, + State: state, + Stderr: &bytes.Buffer{}, + }) + require.NoError(t, err) + require.NotNil(t, entry) + assert.Equal(t, "github-absolute", entry.Name) +} + +// TestBindFailsWhenUnresolvableEntryMightMatch checks that an entry whose "~" path cannot be resolved +// fails the bind when no other entry matches, since the bind cannot rule that entry out. +func TestBindFailsWhenUnresolvableEntryMightMatch(t *testing.T) { + bindingTestConfig(t, bindingTestProfileContents(bindingTestToken)) + t.Setenv(env.HomeEnvVar(), "") + state := &mcp.State{Servers: []mcp.Entry{ + {Name: "github-home", Service: bindingTestService, Profile: bindingTestProfile, Host: bindingTestHost, ConfigFile: "~/.databrickscfg"}, + }} + + _, _, err := mcp.Bind(t.Context(), mcp.BindOptions{ + Profile: bindingTestProfile, + Service: bindingTestService, + State: state, + Stderr: &bytes.Buffer{}, + }) + requireBindError(t, err, mcp.BindUncategorized) + assert.Contains(t, err.Error(), "MCP server github-home: cannot find homedir: $HOME is not set") +} + +// TestBindProfileWithoutHost checks that a profile section with no host is reported as having no host, +// not as missing from the file. +func TestBindProfileWithoutHost(t *testing.T) { + path := bindingTestConfig(t, fmt.Sprintf("[%s]\nauth_type = pat\ntoken = %s\n", bindingTestProfile, bindingTestToken)) + + _, _, err := mcp.Bind(t.Context(), mcp.BindOptions{ + Profile: bindingTestProfile, + Service: bindingTestService, + State: bindingTestState(path, bindingTestHost), + Stderr: &bytes.Buffer{}, + }) + requireBindError(t, err, mcp.BindProfileNotFound) + resolved := filepath.ToSlash(bindingTestResolved(t, path)) + assert.Equal(t, fmt.Sprintf(`MCP server github-logfood is bound to Databricks profile "logfood", which has no host in %s. Recreate it with: DATABRICKS_CONFIG_FILE=%s databricks auth login --host https://adb-123.test --profile logfood or remove the server with: databricks aitools mcp remove --profile logfood`, resolved, resolved), err.Error()) +} + +// TestBindHostMetadataFailureIsNotAuthFailure checks that a host whose metadata cannot be fetched does +// not fail the bind. The SDK logs that failure and goes on, and a profile with a token still binds. +func TestBindHostMetadataFailureIsNotAuthFailure(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.NotFound(w, r) + })) + t.Cleanup(server.Close) + cfgPath := bindingTestConfig(t, fmt.Sprintf("[%s]\nhost = %s\nauth_type = pat\ntoken = %s\n", bindingTestProfile, server.URL, bindingTestToken)) + + cfg, entry, err := mcp.Bind(t.Context(), mcp.BindOptions{ + Profile: bindingTestProfile, + Service: bindingTestService, + State: bindingTestState(cfgPath, server.URL), + Stderr: &bytes.Buffer{}, + }) + require.NoError(t, err) + assert.NotNil(t, entry) + assert.Equal(t, bindingTestToken, cfg.Token) +} + +// TestBindConfigErrorIsUncategorized checks that a configuration error from the SDK, here an +// environment value that does not parse, is reported as uncategorized, not as an authentication +// failure, so the message does not suggest logging in. +func TestBindConfigErrorIsUncategorized(t *testing.T) { + cfgPath := bindingTestConfig(t, bindingTestProfileContents(bindingTestToken)) + t.Setenv("DATABRICKS_RATE_LIMIT", "soon") + + _, _, err := mcp.Bind(t.Context(), mcp.BindOptions{ + Profile: bindingTestProfile, + Service: bindingTestService, + State: bindingTestState(cfgPath, bindingTestHost), + Stderr: &bytes.Buffer{}, + }) + requireBindError(t, err, mcp.BindUncategorized) + assert.NotContains(t, err.Error(), "Run:") + assert.NotContains(t, err.Error(), "auth login") +} + +// TestBindEntryInOtherConfigFileFailsClosed checks that an entry for the service and profile, pinned to +// another config file, stops the bind when the file in use names no entry. Binding there would be a new +// host with no record of the switch. +func TestBindEntryInOtherConfigFileFailsClosed(t *testing.T) { + recordedPath := bindingTestWriteConfig(t, bindingTestProfileContents(bindingTestToken)) + bindingTestConfig(t, bindingTestProfileContents(bindingTestToken)) + stderr := &bytes.Buffer{} + + _, _, err := mcp.Bind(t.Context(), mcp.BindOptions{ + Profile: bindingTestProfile, + Service: bindingTestService, + State: bindingTestState(recordedPath, bindingTestHost), + Stderr: stderr, + }) + requireBindError(t, err, mcp.BindProfileHostChanged) + assert.Contains(t, err.Error(), "was set up with config file "+filepath.ToSlash(bindingTestResolved(t, recordedPath))) + assert.Empty(t, stderr.String()) +} + +// TestBindEntryForOtherProfileKeepsNotice checks that an entry for a different profile does not stop +// a bind to a profile that has no entry, which still gets the notice. +func TestBindEntryForOtherProfileKeepsNotice(t *testing.T) { + bindingTestConfig(t, bindingTestProfileContents(bindingTestToken)) + state := bindingTestState(bindingTestWriteConfig(t, ""), bindingTestHost) + state.Servers[0].Profile = "other" + stderr := &bytes.Buffer{} + + _, entry, err := mcp.Bind(t.Context(), mcp.BindOptions{ + Profile: bindingTestProfile, + Service: bindingTestService, + State: state, + Stderr: stderr, + }) + require.NoError(t, err) + assert.Nil(t, entry) + assert.Contains(t, stderr.String(), "No install record for system.ai.github") +} + +// TestBindProfileWithEmptyHost checks that a profile whose host is set to nothing is reported as having +// no host, not as a profile whose host changed to "". +func TestBindProfileWithEmptyHost(t *testing.T) { + cfgPath := bindingTestConfig(t, fmt.Sprintf("[%s]\nhost =\nauth_type = pat\ntoken = %s\n", bindingTestProfile, bindingTestToken)) + + _, _, err := mcp.Bind(t.Context(), mcp.BindOptions{ + Profile: bindingTestProfile, + Service: bindingTestService, + State: bindingTestState(cfgPath, bindingTestHost), + Stderr: &bytes.Buffer{}, + }) + requireBindError(t, err, mcp.BindProfileNotFound) + assert.Contains(t, err.Error(), "which has no host in") +} + +// TestBindRecreateHintQuotesValues checks that the recreate hint quotes a profile name that needs it, +// and names the pinned config file it was set up with. +func TestBindRecreateHintQuotesValues(t *testing.T) { + cfgPath := bindingTestConfig(t, bindingTestProfileContents(bindingTestToken)) + state := &mcp.State{Servers: []mcp.Entry{{ + Name: "github-logfood", + Service: bindingTestService, + Profile: "my profile", + Host: bindingTestHost, + ConfigFile: cfgPath, + }}} + + _, _, err := mcp.Bind(t.Context(), mcp.BindOptions{ + Profile: "my profile", + Service: bindingTestService, + State: state, + Stderr: &bytes.Buffer{}, + }) + requireBindError(t, err, mcp.BindProfileNotFound) + want := fmt.Sprintf(`MCP server github-logfood is bound to Databricks profile "my profile", which no longer exists in %s. Recreate it with: DATABRICKS_CONFIG_FILE=%s databricks auth login --host https://adb-123.test --profile 'my profile' or remove the server with: databricks aitools mcp remove --profile 'my profile'`, + filepath.ToSlash(bindingTestResolved(t, cfgPath)), filepath.ToSlash(bindingTestResolved(t, cfgPath))) + assert.Equal(t, want, err.Error()) +} diff --git a/libs/aitools/mcp/configfile.go b/libs/aitools/mcp/configfile.go new file mode 100644 index 00000000000..7244fd9bab2 --- /dev/null +++ b/libs/aitools/mcp/configfile.go @@ -0,0 +1,57 @@ +package mcp + +import ( + "context" + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + + "github.com/databricks/cli/libs/databrickscfg" +) + +// resolveConfigFile returns the absolute path of the config file that name refers to. An empty +// name is the default file, and a leading "~" is the home directory. Symlinks are resolved while +// the path is still as the user wrote it: the OS reads "link/../x" through the link's target, so +// the same file has one path however it is named. A path that does not exist is kept as written, +// since there is no file to resolve and cleaning it could name another file. +func resolveConfigFile(ctx context.Context, name string) (string, error) { + path, err := databrickscfg.ResolveConfigFilePath(ctx, name) + if err != nil { + return "", err + } + resolved, err := filepath.EvalSymlinks(path) + switch { + case err == nil: + return filepath.Abs(resolved) + case errors.Is(err, fs.ErrNotExist): + return absoluteAsWritten(path) + default: + return "", err + } +} + +// absoluteAsWritten makes path absolute by joining it to the working directory, without cleaning it. +func absoluteAsWritten(path string) (string, error) { + if filepath.IsAbs(path) { + return path, nil + } + wd, err := os.Getwd() + if err != nil { + return "", fmt.Errorf("failed to determine working directory: %w", err) + } + return wd + string(filepath.Separator) + path, nil +} + +// samePath reports whether two resolved config file paths name the same file. Existing files are +// compared by identity, which also matches hard links and case variants on case-insensitive file +// systems. Paths that do not exist are compared as text. +func samePath(a, b string) bool { + fa, errA := os.Stat(a) + fb, errB := os.Stat(b) + if errA == nil && errB == nil { + return os.SameFile(fa, fb) + } + return a == b +} diff --git a/libs/aitools/mcp/configfile_test.go b/libs/aitools/mcp/configfile_test.go new file mode 100644 index 00000000000..b1f16412ba3 --- /dev/null +++ b/libs/aitools/mcp/configfile_test.go @@ -0,0 +1,75 @@ +package mcp + +import ( + "os" + "path/filepath" + "testing" + + "github.com/databricks/cli/libs/env" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// TestResolveConfigFileResolvesSymlinkBeforeDotDot checks that ".." after a symlink is taken from the +// link's target, as the OS reads the path, not from the link's own directory. +func TestResolveConfigFileResolvesSymlinkBeforeDotDot(t *testing.T) { + base, err := filepath.EvalSymlinks(t.TempDir()) + require.NoError(t, err) + target := filepath.Join(base, "a", "b") + require.NoError(t, os.MkdirAll(target, 0o755)) + want := filepath.Join(base, "a", ".databrickscfg") + require.NoError(t, os.WriteFile(want, []byte("[logfood]\n"), 0o600)) + link := filepath.Join(base, "link") + if err := os.Symlink(target, link); err != nil { + t.Skipf("cannot create symlink: %v", err) + } + + // filepath.Join would clean the ".." away, so the path is joined by hand. + sep := string(filepath.Separator) + got, err := resolveConfigFile(t.Context(), link+sep+".."+sep+".databrickscfg") + require.NoError(t, err) + assert.Equal(t, want, got) +} + +// TestResolveConfigFileWithoutHomeAndAbsoluteName checks that an absolute name resolves with no home +// directory, and that a "~" name reports the missing home directory. +func TestResolveConfigFileWithoutHomeAndAbsoluteName(t *testing.T) { + ctx := env.WithUserHomeDir(t.Context(), "") + name := filepath.Join(t.TempDir(), ".databrickscfg") + + got, err := resolveConfigFile(ctx, name) + require.NoError(t, err) + assert.True(t, filepath.IsAbs(got)) + + _, err = resolveConfigFile(ctx, "~/.databrickscfg") + require.ErrorIs(t, err, env.ErrNoHomeEnv) +} + +// TestResolveConfigFileKeepsPathThroughMissingDir checks that a path through a missing directory is kept +// as written. Cleaning "missing/.." would name the parent's file, which the OS never opens through a +// missing directory. +func TestResolveConfigFileKeepsPathThroughMissingDir(t *testing.T) { + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "cfg"), []byte("[logfood]\n"), 0o600)) + sep := string(filepath.Separator) + name := dir + sep + "missing" + sep + ".." + sep + "cfg" + + got, err := resolveConfigFile(t.Context(), name) + require.NoError(t, err) + assert.Equal(t, name, got) +} + +// TestSamePathComparesExistingFilesByIdentity checks that two names of one existing file compare equal, +// as a hard link does, while names of files that do not exist are compared as text. +func TestSamePathComparesExistingFilesByIdentity(t *testing.T) { + dir := t.TempDir() + a := filepath.Join(dir, "a") + b := filepath.Join(dir, "b") + require.NoError(t, os.WriteFile(a, []byte("[logfood]\n"), 0o600)) + if err := os.Link(a, b); err != nil { + t.Skipf("cannot create hard link: %v", err) + } + + assert.True(t, samePath(a, b)) + assert.False(t, samePath(filepath.Join(dir, "x"), filepath.Join(dir, "X"))) +} diff --git a/libs/aitools/mcp/state.go b/libs/aitools/mcp/state.go new file mode 100644 index 00000000000..ceeaf7ab69c --- /dev/null +++ b/libs/aitools/mcp/state.go @@ -0,0 +1,205 @@ +package mcp + +import ( + "context" + "errors" + "fmt" + "io/fs" + "strings" + + "github.com/databricks/cli/libs/aitools/installer" + "github.com/databricks/cli/libs/databrickscfg/profile" + "github.com/databricks/databricks-sdk-go/config" +) + +// Drift kinds reported by Reconcile. +const ( + DriftProfileMissing DriftKind = "profile_missing" + DriftHostChanged DriftKind = "host_changed" +) + +// Profile lookups that do not yield a usable profile. +var ( + // errProfileMissing means the config file has no profile of the name, or does not exist. + errProfileMissing = errors.New("profile missing") + // errProfileNoHost means the config file has a section of the name whose host is missing or empty. + errProfileNoHost = errors.New("profile has no host") +) + +// State is the MCP section of the aitools install state. It lives in the same file as +// the skills state, so writers that save the whole file keep it. +type State = installer.MCPState + +// Entry is one installed server: a service bound to one profile for one set of agents. +type Entry = installer.MCPEntry + +// AgentRecord is where an entry was written for one agent. +type AgentRecord = installer.MCPAgentRecord + +// DriftKind names how a state entry no longer matches the profiles file. +type DriftKind string + +// Drift is one state entry that no longer matches the Databricks config file. +type Drift struct { + Kind DriftKind + Entry Entry + // CurrentHost is the profile's host as the config file writes it, when Kind is DriftHostChanged. + CurrentHost string + // CurrentWorkspaceID is the workspace the profile names when Kind is DriftHostChanged: its + // workspace_id, else the workspace in its host query. It is "" when the profile names none. + CurrentWorkspaceID string +} + +// LoadState reads the MCP section of the aitools state file. A missing file or section +// yields an empty state. +func LoadState(ctx context.Context) (*State, error) { + dir, err := installer.GlobalSkillsDir(ctx) + if err != nil { + return nil, err + } + mcp, err := installer.LoadMCPState(dir) + if err != nil { + return nil, err + } + if mcp == nil { + return &State{}, nil + } + return mcp, nil +} + +// SaveState replaces the MCP section of the aitools state file. The skills and plugins records +// are kept as they are on disk, including those written since the caller's LoadState. +func SaveState(ctx context.Context, state *State) error { + dir, err := installer.GlobalSkillsDir(ctx) + if err != nil { + return err + } + return installer.SaveMCPState(dir, state) +} + +// Reconcile reports entries whose profile is gone or has no host, and entries whose profile now +// names another host, or another workspace when both the entry and the profile name one. Each +// entry is checked against the config file it is pinned to; an entry with no pinned file is checked +// against the default file, ~/.databrickscfg, whatever the environment names. Each config file is +// read once. +// +// An entry that cannot be checked, such as one whose "~" path has no home directory to resolve, does +// not stop the others. Its error is joined into the returned error, and the drifts of the other +// entries are still returned. +func Reconcile(ctx context.Context, state *State) ([]Drift, error) { + files := configFiles{} + var drifts []Drift + var errs []error + for _, entry := range state.Servers { + drift, err := checkEntry(ctx, files, entry) + if err != nil { + errs = append(errs, fmt.Errorf("MCP server %s: %w", entry.Name, err)) + continue + } + if drift != nil { + drifts = append(drifts, *drift) + } + } + return drifts, errors.Join(errs...) +} + +// checkEntry returns the drift of one entry, or nil when its profile still names the recorded host +// and workspace. The entry's profile is read from the config file the entry is pinned to. +func checkEntry(ctx context.Context, files configFiles, entry Entry) (*Drift, error) { + path, err := resolveConfigFile(ctx, entry.ConfigFile) + if err != nil { + return nil, err + } + p, err := files.profile(path, entry.Profile) + if errors.Is(err, errProfileMissing) || errors.Is(err, errProfileNoHost) { + return &Drift{Kind: DriftProfileMissing, Entry: entry}, nil + } + if err != nil { + return nil, err + } + return driftOf(entry, p), nil +} + +// configFiles holds the config files that one lookup has read, by resolved path, so that each file is +// parsed once. A nil file is one that does not exist. +type configFiles map[string]*config.File + +// profile returns the profile named name from the config file at path. It returns errProfileMissing +// when the file does not exist or has no section of that name, and errProfileNoHost when the section +// has no host or an empty one. +func (c configFiles) profile(path, name string) (profile.Profile, error) { + file, ok := c[path] + if !ok { + loaded, err := config.LoadFile(path) + switch { + case errors.Is(err, fs.ErrNotExist): + loaded = nil + case err != nil: + return profile.Profile{}, fmt.Errorf("failed to read Databricks profiles: %w", err) + } + file = loaded + c[path] = file + } + if file == nil { + return profile.Profile{}, errProfileMissing + } + section, err := file.GetSection(name) + if err != nil { + return profile.Profile{}, errProfileMissing + } + keys := section.KeysHash() + if keys["host"] == "" { + return profile.Profile{}, errProfileNoHost + } + return profile.Profile{Name: name, Host: keys["host"], WorkspaceID: keys["workspace_id"]}, nil +} + +// driftOf returns the drift of an entry against the profile it names, or nil when the profile still +// names the recorded host and workspace. +func driftOf(entry Entry, p profile.Profile) *Drift { + recordedHost, recordedWorkspaceID := recordedTarget(entry) + host, workspaceID := profileTarget(p) + if NormalizeHost(recordedHost) == NormalizeHost(host) && !workspaceChanged(recordedWorkspaceID, workspaceID) { + return nil + } + return &Drift{Kind: DriftHostChanged, Entry: entry, CurrentHost: p.Host, CurrentWorkspaceID: workspaceID} +} + +// recordedTarget returns the host and workspace ID that an entry recorded, resolved as the SDK resolves +// a profile's, so that a workspace named in the recorded host's query is compared too. +func recordedTarget(entry Entry) (host, workspaceID string) { + return profileTarget(profile.Profile{Host: entry.Host, WorkspaceID: entry.WorkspaceID}) +} + +// profileTarget returns the host and workspace ID that the SDK resolves for a profile. It runs the +// SDK's host handling only, so it makes no network request: the SDK keeps a workspace_id the profile +// sets, and otherwise takes the workspace from the host query. The host has its query removed. The +// workspace is "" when the profile names none, or names "none". +func profileTarget(p profile.Profile) (host, workspaceID string) { + c := &config.Config{Host: p.Host, WorkspaceID: p.WorkspaceID} + host = c.CanonicalHostName() + return host, namedWorkspaceID(c.WorkspaceID) +} + +// workspaceChanged reports whether the recorded and current workspace IDs both name a workspace and +// the two differ. A workspace that is not named is not compared. +func workspaceChanged(recorded, current string) bool { + recorded = namedWorkspaceID(recorded) + return recorded != "" && current != "" && recorded != current +} + +// namedWorkspaceID returns the workspace ID a value names, or "" when it names none. The "none" +// sentinel that the CLI writes to skip workspace selection names none. +func namedWorkspaceID(id string) string { + if id == profile.WorkspaceIDNone { + return "" + } + return id +} + +// NormalizeHost returns the form in which two hosts compare equal for drift and binding +// checks. It applies the SDK's host canonicalization (scheme and trailing slash), then +// lowercases the result, because hostnames are case-insensitive. +func NormalizeHost(host string) string { + return strings.ToLower((&config.Config{Host: host}).CanonicalHostName()) +} diff --git a/libs/aitools/mcp/state_test.go b/libs/aitools/mcp/state_test.go new file mode 100644 index 00000000000..06cca4350d7 --- /dev/null +++ b/libs/aitools/mcp/state_test.go @@ -0,0 +1,354 @@ +package mcp_test + +import ( + "context" + "encoding/json" + "fmt" + "os" + "path/filepath" + "testing" + "time" + + "github.com/databricks/cli/libs/aitools/installer" + "github.com/databricks/cli/libs/aitools/mcp" + "github.com/databricks/cli/libs/env" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const ( + stateTestFileRel = ".databricks/aitools/skills/.state.json" + stateTestWorkspaceID = "123" + stateTestOtherProfile = "dogfood" + stateTestOtherHost = "https://adb-456.test" +) + +// stateTestCtx returns a context whose home directory is a fresh temp dir, plus the path of +// the aitools state file inside it. +func stateTestCtx(t *testing.T) (context.Context, string) { + t.Helper() + home := t.TempDir() + return env.WithUserHomeDir(t.Context(), home), filepath.Join(home, stateTestFileRel) +} + +func stateTestEntry() mcp.Entry { + return mcp.Entry{ + Name: "github-logfood", + Service: bindingTestService, + Profile: bindingTestProfile, + Host: bindingTestHost, + WorkspaceID: stateTestWorkspaceID, + SignInRequired: true, + Command: "/usr/local/bin/databricks", + Agents: map[string]mcp.AgentRecord{ + "claude-code": {Path: "/home/me/.claude.json", Scope: "user"}, + }, + InstalledAt: time.Date(2026, 11, 12, 10, 12, 0, 0, time.UTC), + CLIVersion: "0.300.0", + } +} + +// stateTestEntryWith returns the test entry with its profile, host and workspace replaced. +func stateTestEntryWith(profileName, host, workspaceID string) mcp.Entry { + entry := stateTestEntry() + entry.Profile = profileName + entry.Host = host + entry.WorkspaceID = workspaceID + return entry +} + +// writeStateFile writes raw JSON to the aitools state file at path. +func writeStateFile(t *testing.T, path, raw string) { + t.Helper() + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) + require.NoError(t, os.WriteFile(path, []byte(raw), 0o600)) +} + +func TestLoadStateMissingFileIsEmpty(t *testing.T) { + ctx, _ := stateTestCtx(t) + + state, err := mcp.LoadState(ctx) + require.NoError(t, err) + assert.Empty(t, state.Servers) +} + +func TestSaveStateThenLoadStateRoundTrips(t *testing.T) { + ctx, _ := stateTestCtx(t) + + saved := &mcp.State{Servers: []mcp.Entry{stateTestEntry()}} + require.NoError(t, mcp.SaveState(ctx, saved)) + + loaded, err := mcp.LoadState(ctx) + require.NoError(t, err) + assert.Equal(t, saved, loaded) +} + +// TestSaveStateKeepsInstallerRecords checks that an MCP save changes only the MCP section of the +// shared file. +func TestSaveStateKeepsInstallerRecords(t *testing.T) { + ctx, _ := stateTestCtx(t) + dir, err := installer.GlobalSkillsDir(ctx) + require.NoError(t, err) + original := &installer.InstallState{ + SchemaVersion: installer.CurrentSchemaVersion, + Release: "v0.2.0", + LastUpdated: time.Date(2026, 11, 12, 9, 0, 0, 0, time.UTC), + Skills: map[string]string{"databricks": "1.0.0"}, + RepoDirs: map[string]string{"databricks": "skills"}, + Scope: installer.ScopeGlobal, + Plugins: map[string]installer.PluginRecord{ + "claude-code": {Marketplace: "databricks", Plugin: "databricks", Scope: "user", Version: "1.0.0"}, + }, + Files: map[string]installer.FileRecord{ + "databricks/SKILL.md": {SHA256: "abc123", Origin: "skills"}, + }, + } + require.NoError(t, installer.SaveState(dir, original)) + + require.NoError(t, mcp.SaveState(ctx, &mcp.State{Servers: []mcp.Entry{stateTestEntry()}})) + + loaded, err := installer.LoadState(dir) + require.NoError(t, err) + original.MCP = &installer.MCPState{Servers: []installer.MCPEntry{stateTestEntry()}} + assert.Equal(t, original, loaded) +} + +// TestSaveStateUpgradesV2FileToV3 checks that the first MCP save on a v2 file writes schema v3. +func TestSaveStateUpgradesV2FileToV3(t *testing.T) { + ctx, path := stateTestCtx(t) + writeStateFile(t, path, `{"schema_version": 2, "release": "v0.2.0", "skills": {"databricks": "1.0.0"}}`) + + require.NoError(t, mcp.SaveState(ctx, &mcp.State{Servers: []mcp.Entry{stateTestEntry()}})) + + data, err := os.ReadFile(path) + require.NoError(t, err) + var raw map[string]any + require.NoError(t, json.Unmarshal(data, &raw)) + assert.EqualValues(t, 3, raw["schema_version"]) + assert.Equal(t, map[string]any{"databricks": "1.0.0"}, raw["skills"]) + assert.Contains(t, raw, "mcp") +} + +// stateTestProfiles is the profiles file used by the drift tests. The profiles named +// spog-query, spog-none, spog-both and spog-abc name their workspace in the host query instead of +// workspace_id. +// stateTestWriteProfiles writes the profiles that the Reconcile tests check to the default config file +// of the test home directory. +func stateTestWriteProfiles(t *testing.T, ctx context.Context) { + t.Helper() + home, err := env.UserHomeDir(ctx) + require.NoError(t, err) + writeStateFile(t, filepath.Join(home, ".databrickscfg"), fmt.Sprintf(`[%s] +host = %s +workspace_id = %s + +[%s] +host = %s +workspace_id = 456 + +[spog-query] +host = https://spog.test/?o=222 + +[spog-none] +host = https://spog.test/?w=none + +[spog-both] +host = https://spog.test/?o=111&w=222 + +[spog-abc] +host = https://spog.test/?o=abc&w=222 +`, bindingTestProfile, bindingTestHost, stateTestWorkspaceID, stateTestOtherProfile, stateTestOtherHost)) +} + +func TestReconcile(t *testing.T) { + ctx, _ := stateTestCtx(t) + stateTestWriteProfiles(t, ctx) + tests := []struct { + name string + entry mcp.Entry + wantKind mcp.DriftKind + wantHost string + wantWorkspaceID string + }{ + { + name: "matching host and workspace", + entry: stateTestEntryWith(bindingTestProfile, "https://adb-123.test/", stateTestWorkspaceID), + }, + { + name: "host differs only in case", + entry: stateTestEntryWith(bindingTestProfile, "https://ADB-123.test", stateTestWorkspaceID), + }, + { + name: "workspace not compared when the entry names none", + entry: stateTestEntryWith(bindingTestProfile, bindingTestHost, "none"), + }, + { + name: "workspace from host query matches the entry", + entry: stateTestEntryWith("spog-query", "https://spog.test", "222"), + }, + { + name: "workspace from host query differs from the entry", + entry: stateTestEntryWith("spog-query", "https://spog.test", stateTestWorkspaceID), + wantKind: mcp.DriftHostChanged, + wantHost: "https://spog.test/?o=222", + wantWorkspaceID: "222", + }, + { + name: "host query naming none is not compared", + entry: stateTestEntryWith("spog-none", "https://spog.test", stateTestWorkspaceID), + }, + { + name: "w in the host query wins over o", + entry: stateTestEntryWith("spog-both", "https://spog.test", "222"), + }, + { + name: "w in the host query differs from the o the entry recorded", + entry: stateTestEntryWith("spog-both", "https://spog.test", "111"), + wantKind: mcp.DriftHostChanged, + wantHost: "https://spog.test/?o=111&w=222", + wantWorkspaceID: "222", + }, + { + name: "non-numeric o is ignored when w names the workspace", + entry: stateTestEntryWith("spog-abc", "https://spog.test", "222"), + }, + { + name: "profile missing", + entry: stateTestEntryWith("gone", bindingTestHost, stateTestWorkspaceID), + wantKind: mcp.DriftProfileMissing, + }, + { + name: "host changed", + entry: stateTestEntryWith(stateTestOtherProfile, bindingTestHost, stateTestWorkspaceID), + wantKind: mcp.DriftHostChanged, + wantHost: stateTestOtherHost, + wantWorkspaceID: "456", + }, + { + name: "workspace changed on the same host", + entry: stateTestEntryWith(bindingTestProfile, bindingTestHost, "999"), + wantKind: mcp.DriftHostChanged, + wantHost: bindingTestHost, + wantWorkspaceID: stateTestWorkspaceID, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + state := &mcp.State{Servers: []mcp.Entry{tt.entry}} + + drifts, err := mcp.Reconcile(ctx, state) + require.NoError(t, err) + if tt.wantKind == "" { + assert.Empty(t, drifts) + return + } + assert.Equal(t, []mcp.Drift{{ + Kind: tt.wantKind, + Entry: tt.entry, + CurrentHost: tt.wantHost, + CurrentWorkspaceID: tt.wantWorkspaceID, + }}, drifts) + }) + } +} + +func TestReconcileWithoutConfigFileReportsEveryProfileMissing(t *testing.T) { + ctx, _ := stateTestCtx(t) + ctx = env.Set(ctx, "DATABRICKS_CONFIG_FILE", filepath.Join(t.TempDir(), "absent")) + entry := stateTestEntry() + state := &mcp.State{Servers: []mcp.Entry{entry}} + + drifts, err := mcp.Reconcile(ctx, state) + require.NoError(t, err) + assert.Equal(t, []mcp.Drift{{Kind: mcp.DriftProfileMissing, Entry: entry}}, drifts) +} + +// TestReconcileChecksEntryAgainstPinnedConfigFile checks that an entry pinned to a config file +// is checked against that file, not the one the environment names. +func TestReconcileChecksEntryAgainstPinnedConfigFile(t *testing.T) { + pinned := bindingTestWriteConfig(t, bindingTestProfileContents(bindingTestToken)) + ctx := env.Set(t.Context(), "DATABRICKS_CONFIG_FILE", filepath.Join(t.TempDir(), "absent")) + entry := stateTestEntry() + entry.ConfigFile = pinned + state := &mcp.State{Servers: []mcp.Entry{entry}} + + drifts, err := mcp.Reconcile(ctx, state) + require.NoError(t, err) + assert.Empty(t, drifts) +} + +// TestReconcileUnpinnedEntryChecksDefaultConfigFile checks that an entry with no pinned config file +// is checked against ~/.databrickscfg, even when DATABRICKS_CONFIG_FILE names another file. +func TestReconcileUnpinnedEntryChecksDefaultConfigFile(t *testing.T) { + ctx, _ := stateTestCtx(t) + home, err := env.UserHomeDir(ctx) + require.NoError(t, err) + writeStateFile(t, filepath.Join(home, ".databrickscfg"), "[logfood]\nhost = https://adb-456.test\n") + ambient := bindingTestWriteConfig(t, bindingTestProfileContents(bindingTestToken)) + ctx = env.Set(ctx, "DATABRICKS_CONFIG_FILE", ambient) + state := &mcp.State{Servers: []mcp.Entry{stateTestEntry()}} + + drifts, err := mcp.Reconcile(ctx, state) + require.NoError(t, err) + assert.Equal(t, []mcp.Drift{{ + Kind: mcp.DriftHostChanged, + Entry: stateTestEntry(), + CurrentHost: "https://adb-456.test", + CurrentWorkspaceID: "", + }}, drifts) +} + +func TestNormalizeHostIgnoresSchemeCaseAndTrailingSlash(t *testing.T) { + assert.Equal(t, mcp.NormalizeHost("https://ADB-123.test/"), mcp.NormalizeHost("adb-123.test")) + assert.NotEqual(t, mcp.NormalizeHost("https://adb-123.test"), mcp.NormalizeHost("https://adb-456.test")) +} + +// TestReconcileProfileWithoutHostIsMissing checks that a profile section with no host is reported as +// missing, since it names no host to compare. It reads a real file, because the in-memory profiler +// does not model sections without a host. +func TestReconcileProfileWithEmptyHostIsMissing(t *testing.T) { + ctx, _ := stateTestCtx(t) + path := bindingTestWriteConfig(t, "[logfood]\nhost =\nauth_type = pat\ntoken = dapi-profile-token\n") + ctx = env.Set(ctx, "DATABRICKS_CONFIG_FILE", path) + entry := stateTestEntry() + state := &mcp.State{Servers: []mcp.Entry{entry}} + + drifts, err := mcp.Reconcile(ctx, state) + require.NoError(t, err) + assert.Equal(t, []mcp.Drift{{Kind: mcp.DriftProfileMissing, Entry: entry}}, drifts) +} + +func TestReconcileProfileWithoutHostIsMissing(t *testing.T) { + ctx, _ := stateTestCtx(t) + path := bindingTestWriteConfig(t, "[logfood]\nauth_type = pat\ntoken = dapi-profile-token\n") + ctx = env.Set(ctx, "DATABRICKS_CONFIG_FILE", path) + entry := stateTestEntry() + state := &mcp.State{Servers: []mcp.Entry{entry}} + + drifts, err := mcp.Reconcile(ctx, state) + require.NoError(t, err) + assert.Equal(t, []mcp.Drift{{Kind: mcp.DriftProfileMissing, Entry: entry}}, drifts) +} + +// TestReconcileReportsEntryErrorAndKeepsOthers checks that an entry that cannot be checked, here a "~" +// path with no home directory, is reported as an error without stopping the check of the other entries. +func TestReconcileReportsEntryErrorAndKeepsOthers(t *testing.T) { + ctx, _ := stateTestCtx(t) + ctx = env.WithUserHomeDir(ctx, "") + unresolvable := stateTestEntry() + unresolvable.Name = "github-home" + unresolvable.ConfigFile = "~/.databrickscfg" + changed := stateTestEntryWith(bindingTestProfile, "https://adb-999.test", stateTestWorkspaceID) + changed.ConfigFile = bindingTestWriteConfig(t, fmt.Sprintf("[%s]\nhost = %s\nworkspace_id = %s\nauth_type = pat\ntoken = %s\n", bindingTestProfile, bindingTestHost, stateTestWorkspaceID, bindingTestToken)) + state := &mcp.State{Servers: []mcp.Entry{unresolvable, changed}} + + drifts, err := mcp.Reconcile(ctx, state) + require.ErrorIs(t, err, env.ErrNoHomeEnv) + assert.Contains(t, err.Error(), "MCP server github-home: ") + assert.Equal(t, []mcp.Drift{{ + Kind: mcp.DriftHostChanged, + Entry: changed, + CurrentHost: bindingTestHost, + CurrentWorkspaceID: stateTestWorkspaceID, + }}, drifts) +} diff --git a/libs/aitools/mcpconfig/spec.go b/libs/aitools/mcpconfig/spec.go index 9eb80bab97d..07c9a910f33 100644 --- a/libs/aitools/mcpconfig/spec.go +++ b/libs/aitools/mcpconfig/spec.go @@ -9,6 +9,11 @@ import ( "strings" ) +// ConfigFileEnv is the environment variable that selects the Databricks config file. An agent +// entry pins its value when this CLI sees it set, and the MCP binding reads the same variable. +// A write that does not pin it removes it; other variables are the user's. +const ConfigFileEnv = "DATABRICKS_CONFIG_FILE" + // Format is the on-disk format of an agent's MCP config file. type Format int diff --git a/libs/databrickscfg/ops.go b/libs/databrickscfg/ops.go index 2d6faf1ba9c..95a224babd9 100644 --- a/libs/databrickscfg/ops.go +++ b/libs/databrickscfg/ops.go @@ -147,7 +147,7 @@ func GetSectionNames(ctx context.Context, configFilePath string) ([]string, erro // loadConfigFile loads a config file without creating it if it doesn't exist. // Returns (nil, nil) when the file is not found. func loadConfigFile(ctx context.Context, filename string) (*config.File, error) { - filename, err := resolveConfigFilePath(ctx, filename) + filename, err := ResolveConfigFilePath(ctx, filename) if err != nil { return nil, err } @@ -161,8 +161,9 @@ func loadConfigFile(ctx context.Context, filename string) (*config.File, error) return configFile, nil } -// resolveConfigFilePath defaults to ~/.databrickscfg and expands ~ to the home directory. -func resolveConfigFilePath(ctx context.Context, filename string) (string, error) { +// ResolveConfigFilePath defaults to ~/.databrickscfg and expands ~ to the home directory. +// It does not make the path absolute or resolve symlinks. +func ResolveConfigFilePath(ctx context.Context, filename string) (string, error) { if filename == "" { filename = "~/.databrickscfg" } @@ -346,7 +347,7 @@ func ClearDefaultProfile(ctx context.Context, profileName, configFilePath string } func loadOrCreateConfigFile(ctx context.Context, filename string) (*config.File, error) { - filename, err := resolveConfigFilePath(ctx, filename) + filename, err := ResolveConfigFilePath(ctx, filename) if err != nil { return nil, err }