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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions acceptance/cmd/api/not-an-agent/out.test.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Cloud = false
39 changes: 39 additions & 0 deletions acceptance/cmd/api/not-an-agent/output.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@

=== With the variable set, the request has no agent token

>>> DATABRICKS_NOT_AN_AGENT=1 CLAUDECODE=1 [CLI] api get /api/2.0/clusters/list
{
"headers": {
"Authorization": [
"Bearer [DATABRICKS_TOKEN]"
],
"User-Agent": [
"cli/[CLI_VERSION] databricks-sdk-go/[SDK_VERSION] go/[GO_VERSION] os/[OS] cmd/api_get cmd-exec-id/[UUID][0] interactive/none auth/pat"
],
"X-Databricks-Workspace-Id": [
"[WORKSPACE_ID]"
]
},
"method": "GET",
"path": "/api/2.0/clusters/list"
}

=== With the variable unset, the request carries the agent token

>>> CLAUDECODE=1 [CLI] api get /api/2.0/clusters/list
Databricks skills are not installed. To work with Databricks reliably, first run: databricks aitools install
{
"headers": {
"Authorization": [
"Bearer [DATABRICKS_TOKEN]"
],
"User-Agent": [
"cli/[CLI_VERSION] databricks-sdk-go/[SDK_VERSION] go/[GO_VERSION] os/[OS] cmd/api_get cmd-exec-id/[UUID][1] interactive/none aitools-agent/none auth/pat agent/claude-code"
],
"X-Databricks-Workspace-Id": [
"[WORKSPACE_ID]"
]
},
"method": "GET",
"path": "/api/2.0/clusters/list"
}
9 changes: 9 additions & 0 deletions acceptance/cmd/api/not-an-agent/script
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# The api command builds its own SDK client, so DATABRICKS_NOT_AN_AGENT must drop the agent token from its User-Agent.
title "With the variable set, the request has no agent token"
# MSYS_NO_PATHCONV stops Git Bash on Windows from rewriting the leading slash of the API path.
MSYS_NO_PATHCONV=1 trace DATABRICKS_NOT_AN_AGENT=1 CLAUDECODE=1 $CLI api get /api/2.0/clusters/list > /dev/null
print_requests.py --get //api/2.0/clusters/list | contains.py '!agent/claude-code'

title "With the variable unset, the request carries the agent token"
MSYS_NO_PATHCONV=1 trace CLAUDECODE=1 $CLI api get /api/2.0/clusters/list > /dev/null
print_requests.py --get //api/2.0/clusters/list | contains.py 'agent/claude-code'
1 change: 1 addition & 0 deletions acceptance/cmd/auth/describe/not-an-agent/out.test.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Cloud = false
26 changes: 26 additions & 0 deletions acceptance/cmd/auth/describe/not-an-agent/output.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@

=== With the variable set, the verification request has no agent token

>>> DATABRICKS_NOT_AN_AGENT=1 CLAUDECODE=1 [CLI] auth describe
{
"headers": {
"User-Agent": [
"cli/[CLI_VERSION] databricks-sdk-go/[SDK_VERSION] go/[GO_VERSION] os/[OS] cmd/auth_describe cmd-exec-id/[UUID][0] interactive/none auth/pat"
]
},
"method": "GET",
"path": "/api/2.0/preview/scim/v2/Me"
}

=== With the variable unset, the verification request carries the agent token

>>> CLAUDECODE=1 [CLI] auth describe
{
"headers": {
"User-Agent": [
"cli/[CLI_VERSION] databricks-sdk-go/[SDK_VERSION] go/[GO_VERSION] os/[OS] cmd/auth_describe cmd-exec-id/[UUID][1] interactive/none aitools-agent/none auth/pat agent/claude-code"
]
},
"method": "GET",
"path": "/api/2.0/preview/scim/v2/Me"
}
8 changes: 8 additions & 0 deletions acceptance/cmd/auth/describe/not-an-agent/script
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# auth describe verifies the workspace credentials with its own SDK client, so the variable must reach it too.
title "With the variable set, the verification request has no agent token"
trace DATABRICKS_NOT_AN_AGENT=1 CLAUDECODE=1 $CLI auth describe > /dev/null
print_requests.py --get //api/2.0/preview/scim/v2/Me | contains.py '!agent/claude-code'

title "With the variable unset, the verification request carries the agent token"
trace CLAUDECODE=1 $CLI auth describe > /dev/null
print_requests.py --get //api/2.0/preview/scim/v2/Me | contains.py 'agent/claude-code'
11 changes: 11 additions & 0 deletions acceptance/cmd/auth/describe/not-an-agent/test.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
RecordRequests = true
IncludeRequestHeaders = ["User-Agent"]

# Normalize OS-dependent and CI-only User-Agent segments so the recorded requests are stable everywhere.
[[Repls]]
Old = '(linux|darwin|windows)'
New = '[OS]'

[[Repls]]
Old = " cicd/[A-Za-z0-9.-]+"
New = ""
2 changes: 2 additions & 0 deletions cmd/aitools/mcp_add.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (

"github.com/databricks/cli/cmd/root"
"github.com/databricks/cli/internal/build"
"github.com/databricks/cli/libs/agent"
"github.com/databricks/cli/libs/aitools/agents"
"github.com/databricks/cli/libs/aitools/installer"
"github.com/databricks/cli/libs/aitools/mcp"
Expand Down Expand Up @@ -590,6 +591,7 @@ func checkWorkspaceProfile(name, configFile string, cfg *config.Config) error {

// boundClient returns the workspace client and Authorization header for the bound config.
func boundClient(ctx context.Context, cfg *config.Config, name, pinnedFile string) (*databricks.WorkspaceClient, string, error) {
agent.ApplyNotAnAgentHeader(ctx, cfg)
w, err := databricks.NewWorkspaceClient((*databricks.Config)(cfg))
if err != nil {
return nil, "", err
Expand Down
6 changes: 4 additions & 2 deletions cmd/aitools/mcp_serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"time"

"github.com/databricks/cli/cmd/root"
"github.com/databricks/cli/libs/agent"
"github.com/databricks/cli/libs/aitools/agents"
"github.com/databricks/cli/libs/aitools/mcp"
"github.com/databricks/cli/libs/aitools/mcp/proxy"
Expand Down Expand Up @@ -250,7 +251,7 @@ func runMcpServe(cmd *cobra.Command, f mcpServeFlags) error {
// needs no sign-in skips the startup service lookup.
var w *databricks.WorkspaceClient
if entry == nil || entry.SignInRequired {
w, err = guardedClient(cfg, refresh)
w, err = guardedClient(ctx, cfg, refresh)
if err != nil {
return serveFailure(cmd, err, 1)
}
Expand Down Expand Up @@ -366,7 +367,7 @@ func checkBindingWithRetry(check func() error) error {
// guardedClient returns the client of the bound profile whose requests the refresh guard authenticates. The SDK calls
// the guard for each request the client makes, so a token that cannot be refreshed stops the proxy from any of them. The
// profile's config is read again for the client, since its own credentials are the guard's.
func guardedClient(cfg *config.Config, refresh *refreshGuard) (*databricks.WorkspaceClient, error) {
func guardedClient(ctx context.Context, cfg *config.Config, refresh *refreshGuard) (*databricks.WorkspaceClient, error) {
guarded, err := mcp.BoundConfig(cfg.Profile, cfg.ConfigFile)
if err != nil {
return nil, err
Expand All @@ -376,6 +377,7 @@ func guardedClient(cfg *config.Config, refresh *refreshGuard) (*databricks.Works
guarded.WorkspaceID = ""
}
guarded.Credentials = guardCredentials{refresh: refresh}
agent.ApplyNotAnAgentHeader(ctx, guarded)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Should fix: the MCP commands' telemetry upload still sends the agent token under DATABRICKS_NOT_AN_AGENT. setUploadConfig (cmd/aitools/mcp_telemetry.go:33) builds a separate config with mcp.BoundUploadConfig and hands it to telemetry.SetUploadConfig. The guard here and in boundClient wraps only the command's own client, so the upload config's HTTPTransport stays nil. newAPIClient in libs/telemetry/logger.go builds its client with config.HTTPClientConfigFromConfig, and that function's visitor adds agent/<name>.

I reproduced it with a scratch test in cmd/aitools. With CLAUDECODE=1, DATABRICKS_NOT_AN_AGENT=1 and a PAT profile, I called setUploadConfig(...) and then telemetry.Send(ctx, cfg, nil) against an httptest server. The server recorded POST /telemetry-ext with User-Agent: cli/... auth/pat agent/claude-code. Upload uses the same newAPIClient, so aitools mcp add, serve, login and remove all send it whenever telemetry is on.

Fix: add one agent.ApplyNotAnAgentHeader(ctx, cfg) on the upload config, either in setUploadConfig right after BoundUploadConfig or inside BoundUploadConfig, which already takes ctx. Then add a set/unset User-Agent check on the /telemetry-ext request, like the other checks in this PR.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 15161a7: setUploadConfig now applies agent.ApplyNotAnAgentHeader to the upload config right after BoundUploadConfig, so the /telemetry-ext request leaves out the agent token under DATABRICKS_NOT_AN_AGENT. Added TestSetUploadConfigNotAnAgentUserAgent, which sends a telemetry request to an httptest server and checks the User-Agent has agent/claude-code with the variable unset and no agent/ token with it set.

return databricks.NewWorkspaceClient((*databricks.Config)(guarded))
}

Expand Down
48 changes: 47 additions & 1 deletion cmd/aitools/mcp_serve_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"time"

"github.com/databricks/cli/cmd/root"
"github.com/databricks/cli/internal/testutil"
"github.com/databricks/cli/libs/aitools/installer"
"github.com/databricks/cli/libs/aitools/mcp"
"github.com/databricks/cli/libs/aitools/mcp/proxy"
Expand Down Expand Up @@ -1738,7 +1739,7 @@ func TestGuardedClientSendsNoSentinelWorkspaceID(t *testing.T) {
require.NoError(t, os.WriteFile(cfgFile, []byte(body), 0o600))
refresh := &refreshGuard{authenticate: func(*http.Request) error { return nil }, profile: testProfile, cancel: func() {}}

w, err := guardedClient(&config.Config{Profile: testProfile, ConfigFile: cfgFile}, refresh)
w, err := guardedClient(t.Context(), &config.Config{Profile: testProfile, ConfigFile: cfgFile}, refresh)
require.NoError(t, err)
_, err = mcp.GetService(t.Context(), w, testService)

Expand Down Expand Up @@ -2006,3 +2007,48 @@ func TestServeSignInPageIsNotCancelledWithTheRequest(t *testing.T) {
require.ErrorIs(t, <-signInErr, context.Canceled)
assert.NoError(t, <-pageErr, "the page is opened with a context the request's cancellation does not reach")
}

// TestGuardedClientNotAnAgentDropsAgentHeader checks that the serve's client leaves the agent token out of User-Agent
// under DATABRICKS_NOT_AN_AGENT, and keeps it without the variable.
func TestGuardedClientNotAnAgentDropsAgentHeader(t *testing.T) {
testutil.SetAgentEnv(t, "CLAUDECODE", "1")

cases := []struct {
name string
noAgent bool
}{
{name: "variable set", noAgent: true},
{name: "variable unset", noAgent: false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
var userAgent string
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
userAgent = r.Header.Get("User-Agent")
rw.WriteHeader(http.StatusNotFound)
_, _ = io.WriteString(rw, `{"error_code":"NOT_FOUND","message":"nope"}`)
}))
t.Cleanup(server.Close)
cfgFile := filepath.Join(t.TempDir(), "cfg")
body := "[" + testProfile + "]\nhost = " + server.URL + "\ntoken = test-token\nworkspace_id = none\n"
require.NoError(t, os.WriteFile(cfgFile, []byte(body), 0o600))
refresh := &refreshGuard{authenticate: func(*http.Request) error { return nil }, profile: testProfile, cancel: func() {}}

ctx := t.Context()
if tc.noAgent {
t.Setenv("DATABRICKS_NOT_AN_AGENT", "1")
}
w, err := guardedClient(ctx, &config.Config{Profile: testProfile, ConfigFile: cfgFile}, refresh)
require.NoError(t, err)
// The service call fails on the 404; only the User-Agent of the request matters here.
_, _ = mcp.GetService(ctx, w, testService)

require.NotEmpty(t, userAgent)
if tc.noAgent {
assert.NotContains(t, userAgent, "agent/")
} else {
assert.Contains(t, userAgent, "agent/claude-code")
}
})
}
}
3 changes: 3 additions & 0 deletions cmd/aitools/mcp_telemetry.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"strings"

"github.com/databricks/cli/libs/agent"
"github.com/databricks/cli/libs/aitools/agents"
"github.com/databricks/cli/libs/aitools/mcp"
"github.com/databricks/cli/libs/auth"
Expand Down Expand Up @@ -36,6 +37,8 @@ func setUploadConfig(ctx context.Context, profileName, configFile string, bound
telemetry.SkipUpload(ctx)
return
}
// The upload builds its own client from this config, so the command's guarded client does not cover it.
agent.ApplyNotAnAgentHeader(ctx, cfg)
if bound == nil {
pat := config.PatCredentials{}
if cfg.Token == "" || (cfg.AuthType != "" && cfg.AuthType != pat.Name()) {
Expand Down
39 changes: 39 additions & 0 deletions cmd/aitools/mcp_telemetry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,15 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"maps"
"net/http"
"net/http/httptest"
"path/filepath"
"slices"
"sync/atomic"
"testing"

"github.com/databricks/cli/internal/testutil"
Expand Down Expand Up @@ -330,6 +333,42 @@ func TestSetUploadConfigLogsNoWarningForFailedHostMetadata(t *testing.T) {
assert.Empty(t, warnings.String())
}

// The upload sends its own request, so under DATABRICKS_NOT_AN_AGENT its User-Agent must leave the agent token out.
func TestSetUploadConfigNotAnAgentUserAgent(t *testing.T) {
for _, notAnAgent := range []bool{false, true} {
t.Run(fmt.Sprintf("not_an_agent=%v", notAnAgent), func(t *testing.T) {
testutil.SetAgentEnv(t, "CLAUDECODE", "1")
var userAgent atomic.Value
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/telemetry-ext" {
userAgent.Store(r.Header.Get("User-Agent"))
}
_, _ = w.Write([]byte(`{}`))
}))
t.Cleanup(server.Close)

home := withHome(t)
writeHomeConfig(t, home, "[logfood]\nhost = "+server.URL+"\nauth_type = pat\ntoken = t\n")
ctx := env.Set(telemetry.WithNewLogger(t.Context()), "DATABRICKS_CLI_DISABLE_TELEMETRY", "")
if notAnAgent {
ctx = env.Set(ctx, "DATABRICKS_NOT_AN_AGENT", "1")
}
setUploadConfig(ctx, "logfood", filepath.Join(home, ".databrickscfg"), nil, "")
cfg, uploads := telemetry.UploadConfig(ctx)
require.True(t, uploads)
require.NoError(t, telemetry.Send(ctx, cfg, nil))

got, _ := userAgent.Load().(string)
require.NotEmpty(t, got)
if notAnAgent {
assert.NotContains(t, got, "agent/")
} else {
assert.Contains(t, got, "agent/claude-code")
}
})
}
}

func TestSignInPromptedEvent(t *testing.T) {
for signedIn, state := range map[bool]protos.AitoolsMcpSignInState{
true: protos.AitoolsMcpSignInStateActive,
Expand Down
2 changes: 2 additions & 0 deletions cmd/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"strings"

"github.com/databricks/cli/cmd/root"
"github.com/databricks/cli/libs/agent"
"github.com/databricks/cli/libs/auth"
"github.com/databricks/cli/libs/cmdio"
"github.com/databricks/cli/libs/databrickscfg"
Expand Down Expand Up @@ -105,6 +106,7 @@ func makeCommand(method string) *cobra.Command {
// Skips the default profile when DATABRICKS_HOST is set (#5616).
root.ResolveDefaultProfile(cmd.Context(), cfg)

agent.ApplyNotAnAgentHeader(cmd.Context(), cfg)
api, err := client.New(cfg)
if err != nil {
return err
Expand Down
8 changes: 6 additions & 2 deletions cmd/auth/docker/docker_profile.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@ import (
"os"
"strings"

"github.com/databricks/cli/libs/agent"
"github.com/databricks/cli/libs/databrickscfg"
"github.com/databricks/cli/libs/databrickscfg/profile"
"github.com/databricks/cli/libs/dockercredentials"
"github.com/databricks/cli/libs/env"
"github.com/databricks/databricks-sdk-go"
"github.com/databricks/databricks-sdk-go/config"
)

// dockerWorkspace holds the selected profile and its resolved workspace ID.
Expand Down Expand Up @@ -62,15 +64,17 @@ func loadDockerWorkspace(ctx context.Context, name string, region *string) (*doc
}
var client *databricks.WorkspaceClient
if region == nil || p.WorkspaceID == "" || p.WorkspaceID == profile.WorkspaceIDNone {
client, err = databricks.NewWorkspaceClient(&databricks.Config{
profileCfg := &config.Config{
Profile: p.Name,
Host: p.Host,
AccountID: p.AccountID,
AuthType: p.AuthType,
ConfigFile: env.Get(ctx, "DATABRICKS_CONFIG_FILE"),
Loaders: databrickscfg.ProfileAuthLoaders,
DatabricksCliPath: executable,
})
}
agent.ApplyNotAnAgentHeader(ctx, profileCfg)
client, err = databricks.NewWorkspaceClient((*databricks.Config)(profileCfg))
if err != nil {
err = fmt.Errorf("load workspace profile %q: %w. Run databricks auth login --host <workspace-url> and retry with that profile", p.Name, err)
return nil, dockercredentials.RewriteProfileError(ctx, p, err)
Expand Down
13 changes: 9 additions & 4 deletions cmd/auth/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"strings"
"time"

"github.com/databricks/cli/libs/agent"
"github.com/databricks/cli/libs/auth"
"github.com/databricks/cli/libs/auth/storage"
"github.com/databricks/cli/libs/auth/u2m"
Expand Down Expand Up @@ -523,12 +524,14 @@ a new profile is created.
// Create a workspace client to list clusters for interactive selection.
// We use a custom CredentialsStrategy that wraps the token we just minted,
// avoiding the need to spawn a child CLI process (which AuthType "databricks-cli" does).
w, err := databricks.NewWorkspaceClient(&databricks.Config{
wCfg := &config.Config{
Host: authArguments.Host,
AccountID: authArguments.AccountID,
WorkspaceID: authArguments.WorkspaceID,
Credentials: config.NewTokenSourceStrategy("login-token", authconv.AuthTokenSource(tokenSource)),
})
}
agent.ApplyNotAnAgentHeader(ctx, wCfg)
w, err := databricks.NewWorkspaceClient((*databricks.Config)(wCfg))
if err != nil {
return err
}
Expand Down Expand Up @@ -1054,7 +1057,7 @@ func promptForWorkspaceSelection(ctx context.Context, authArguments *auth.AuthAr
return "", nil
}

a, err := databricks.NewAccountClient(&databricks.Config{
aCfg := &config.Config{
Host: authArguments.Host,
AccountID: authArguments.AccountID,
Credentials: config.NewTokenSourceStrategy("login-token", authconv.AuthTokenSource(tokenSource)),
Expand All @@ -1063,7 +1066,9 @@ func promptForWorkspaceSelection(ctx context.Context, authArguments *auth.AuthAr
// don't spend the SDK's default 5 minute retry budget on a 503 here.
HTTPTimeoutSeconds: workspaceListTimeoutSeconds,
RetryTimeoutSeconds: workspaceListTimeoutSeconds,
})
}
agent.ApplyNotAnAgentHeader(ctx, aCfg)
a, err := databricks.NewAccountClient((*databricks.Config)(aCfg))
if err != nil {
return "", err
}
Expand Down
Loading
Loading