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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions internal/clientidentity/client_identity.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package clientidentity
import (
"crypto/sha256"
"encoding/hex"
"regexp"
"strings"
)

Expand Down Expand Up @@ -127,6 +128,24 @@ func NormalizeRaw(raw string) string {
return strings.ToLower(strings.TrimSpace(raw))
}

// mcpRemoteSuffix matches the " (via mcp-remote <version>)" tag mcp-remote
// appends to the clientInfo.name of the client it bridges (GH #1786). The
// separators are single spaces and the version is printable ASCII without
// parentheses, so a tag carrying a control character never matches.
var mcpRemoteSuffix = regexp.MustCompile(`^(.*[^ ]) \(via mcp-remote(?: [!-'*-~]+)?\)$`)

// AliasCandidate is NormalizeRaw with one trailing mcp-remote bridge tag
// removed, so "claude-ai (via mcp-remote 0.15.2)" classifies as the client
// behind the bridge. Use it only to look up supported aliases: like
// NormalizeRaw it preserves controls, and unknown names keep their exact key.
func AliasCandidate(raw string) string {
normalized := NormalizeRaw(raw)
if m := mcpRemoteSuffix.FindStringSubmatch(normalized); m != nil {
return m[1]
}
return normalized
}

// SanitizeDisplay keeps rendered names safe and bounded.
func SanitizeDisplay(raw string) string {
var b strings.Builder
Expand Down
32 changes: 32 additions & 0 deletions internal/clientidentity/client_identity_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,35 @@ func TestFromRawKeepsTransformedAndFormerSuffixLookalikeDistinct(t *testing.T) {
require.Equal(t, "~p:"+transformed.PublicID, sentinelLookalike.PublicID)
require.NotEqual(t, transformedWithSentinelDisplay.PublicID, sentinelDisplayLookalike.PublicID, "a transformed display beginning with the sentinel must not recreate an escaped ordinary ID")
}

func TestAliasCandidateStripsOneMCPRemoteBridgeSuffix(t *testing.T) {
cases := map[string]string{
"claude-ai (via mcp-remote 0.15.2)": "claude-ai",
" Claude-AI (via mcp-remote 0.1.29) ": "claude-ai",
"claude-ai (via mcp-remote)": "claude-ai",
"codex-mcp-client": "codex-mcp-client",
"Cursor": "cursor",
"claude-ai (via something-else 1.0)": "claude-ai (via something-else 1.0)",
"claude-ai (via mcp-remote 1) (via mcp-remote 2)": "claude-ai (via mcp-remote 1)",
"(via mcp-remote 0.15.2)": "(via mcp-remote 0.15.2)",
"claude-ai(via mcp-remote 0.15.2)": "claude-ai(via mcp-remote 0.15.2)",
"claude-ai (via mcp-remote 0.15.2) x": "claude-ai (via mcp-remote 0.15.2) x",
}
for raw, want := range cases {
require.Equal(t, want, AliasCandidate(raw), raw)
}
// Controls survive, so an escape-prefixed bridged name cannot pass as a
// supported alias once the suffix is removed.
require.Equal(t, "\x1bclaude-ai", AliasCandidate("\x1bclaude-ai (via mcp-remote 0.15.2)"))
for _, raw := range []string{
"claude-ai\n(via mcp-remote 0.15.2)",
"claude-ai\t(via mcp-remote 0.15.2)",
"claude-ai (via mcp-remote 0.15.2)",
"claude-ai (via mcp-remote \x00)",
"claude-ai (via mcp-remote 0.15\x1b2)",
"claude-ai (via mcp-remote 0.15.2\n)",
"claude-ai (via mcp-remote 0.15.2)",
} {
require.Equal(t, NormalizeRaw(raw), AliasCandidate(raw), "%q must not strip to a supported alias", raw)
}
}
19 changes: 11 additions & 8 deletions internal/connect/clients.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,9 @@ var allClients = []ClientDef{
Bridge: true,
Icon: "claude-desktop",
// "claude-ai" is Anthropic's published clientInfo.name for the Claude
// Desktop app's MCP client.
// Desktop app's MCP client. Through the mcp-remote bridge Connect
// writes, it arrives as "claude-ai (via mcp-remote <version>)";
// clientidentity.AliasCandidate strips that tag before matching.
ClientInfoNames: []string{"claude-ai", "Claude"},
ReloadHint: "Restart Claude Desktop to load MCPProxy",
},
Expand Down Expand Up @@ -105,13 +107,14 @@ var allClients = []ClientDef{
ReloadHint: "Run \"MCP: List Servers\" → Restart (or reload the window) in VS Code to load MCPProxy",
},
{
ID: "codex",
Name: "Codex CLI",
Format: "toml",
ServerKey: "mcp_servers",
Supported: true,
Icon: "codex",
ClientInfoNames: []string{"codex", "codex-cli"},
ID: "codex",
Name: "Codex CLI",
Format: "toml",
ServerKey: "mcp_servers",
Supported: true,
Icon: "codex",
// Codex CLI's rmcp client sends "codex-mcp-client" (GH #1786).
ClientInfoNames: []string{"codex", "codex-cli", "codex-mcp-client"},
ReloadHint: "Restart Codex CLI to load MCPProxy",
},
{
Expand Down
5 changes: 3 additions & 2 deletions internal/httpapi/clients.go
Original file line number Diff line number Diff line change
Expand Up @@ -568,7 +568,7 @@ func (s *Server) clientPresence(withSessions bool, detailID string) ([]clientPre
}
for _, session := range sessions {
identity := clientidentity.FromRaw(session.ClientName)
if identity.Key == "" || known[identity.RawNormalized] {
if identity.Key == "" || known[clientidentity.AliasCandidate(session.ClientName)] {
continue
}
id := "other:" + identity.PublicID
Expand Down Expand Up @@ -635,8 +635,9 @@ func latestClientSeen(seen map[string]time.Time, aliases []string) *time.Time {
return &latest
}
func clientMatches(name string, aliases []string) bool {
candidate := clientidentity.AliasCandidate(name)
for _, alias := range aliases {
if strings.EqualFold(strings.TrimSpace(name), alias) {
if candidate == clientidentity.NormalizeRaw(alias) {
return true
}
}
Expand Down
51 changes: 51 additions & 0 deletions internal/httpapi/clients_presence_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -516,3 +516,54 @@ func successData(t *testing.T, rec *httptest.ResponseRecorder) map[string]any {
require.True(t, envelope.Success)
return envelope.Data
}

func TestClientsPresence_CreditsBridgedClaudeDesktopAndCodex(t *testing.T) {
rt, err := proxyRuntime.New(&config.Config{DataDir: t.TempDir(), Listen: "127.0.0.1:0"}, "", zap.NewNop())
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, rt.Close()) })

rt.RecordClientSeen("claude-ai (via mcp-remote 0.15.2)")
rt.RecordClientSeen("codex-mcp-client")
state, err := rt.GetOnboardingState()
require.NoError(t, err)
ctrl := &clientPresenceController{state: state, sessions: []*contracts.MCPSession{
{ID: "desktop", ClientName: "claude-ai (via mcp-remote 0.15.2)", Status: "active", StartTime: time.Now().Add(-time.Minute), LastActivity: time.Now()},
{ID: "codex", ClientName: "codex-mcp-client", Status: "active", StartTime: time.Now().Add(-time.Minute), LastActivity: time.Now()},
}}
srv := NewServer(ctrl, zap.NewNop().Sugar(), nil)
req := httptest.NewRequest(http.MethodGet, "/api/v1/clients", nil)
req.Header.Set("X-API-Key", "clients-admin-key")
rec := httptest.NewRecorder()
srv.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())

rows := map[string]map[string]any{}
for _, raw := range successData(t, rec)["clients"].([]any) {
row := raw.(map[string]any)
require.NotEqual(t, "other", row["kind"], "bridged and Codex sessions must not become other: rows: %v", row["id"])
rows[row["id"].(string)] = row
}
for _, id := range []string{"claude-desktop", "codex"} {
require.Contains(t, rows, id)
require.NotNil(t, rows[id]["last_seen"], id)
require.Equal(t, float64(1), rows[id]["active_sessions"], id)
}
}

func TestClientsPresence_EscapePrefixedBridgedAliasRemainsOtherClient(t *testing.T) {
ctrl := &clientPresenceController{sessions: []*contracts.MCPSession{{
ID: "escaped", ClientName: "\x1bclaude-ai (via mcp-remote 0.15.2)", Status: "active", StartTime: time.Now().Add(-time.Minute), LastActivity: time.Now(),
}}}
srv := NewServer(ctrl, zap.NewNop().Sugar(), nil)
req := httptest.NewRequest(http.MethodGet, "/api/v1/clients", nil)
req.Header.Set("X-API-Key", "clients-admin-key")
rec := httptest.NewRecorder()
srv.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
for _, raw := range successData(t, rec)["clients"].([]any) {
row := raw.(map[string]any)
if row["id"] == "claude-desktop" {
require.Equal(t, float64(0), row["active_sessions"], "escaped name must not credit Claude Desktop")
}
}
}
18 changes: 18 additions & 0 deletions internal/runtime/clients_presence_generation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,21 @@ func TestRecordClientSeenCapsOtherNamesWithoutEvictingKnownAliases(t *testing.T)
require.LessOrEqual(t, len(state.ClientLastSeen), 32)
require.Contains(t, state.ClientLastSeen, "cursor")
}

func TestRecordClientSeenCreditsBridgedAndCodexClientNames(t *testing.T) {
mgr, err := storage.NewManager(t.TempDir(), zap.NewNop().Sugar())
require.NoError(t, err)
t.Cleanup(func() { _ = mgr.Close() })
r := &Runtime{storageManager: mgr, logger: zap.NewNop()}
r.RecordClientSeen("claude-ai (via mcp-remote 0.15.2)")
r.RecordClientSeen("codex-mcp-client")
r.RecordClientSeen("\x1bclaude-ai (via mcp-remote 0.15.2)")

state, err := mgr.GetOnboardingState()
require.NoError(t, err)
require.Contains(t, state.ClientLastSeen, "claude-ai")
require.Contains(t, state.ClientLastSeen, "codex-mcp-client")
require.NotNil(t, latestSeenForAliases(state.ClientLastSeen, []string{"claude-ai", "Claude"}))
require.NotContains(t, state.ClientLastSeen, "v1:p:claude-ai (via mcp-remote 0.15.2)", "a bridged known client must not keep an other: key")
require.Len(t, state.ClientLastSeen, 3, "the escape-prefixed name stays a distinct unknown client")
}
4 changes: 2 additions & 2 deletions internal/runtime/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -4567,8 +4567,8 @@ func sanitizeClientName(raw string) string {
if identity.Key == "" {
return ""
}
if isKnownClientAlias(identity.RawNormalized) {
return identity.RawNormalized
if alias := clientidentity.AliasCandidate(raw); isKnownClientAlias(alias) {
return alias
}
return identity.Key
}
Expand Down
4 changes: 4 additions & 0 deletions internal/runtime/usage_aggregate.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package runtime

import (
"github.com/smart-mcp-proxy/mcpproxy-go/internal/clientidentity"
"math"
"sort"
"strings"
Expand Down Expand Up @@ -281,6 +282,9 @@ func (a *UsageAggregate) applyClientCalls(rec *storage.ActivityRecord) {
if client == "" {
return
}
if alias := clientidentity.AliasCandidate(raw); alias != client && knownClientAliases()[alias] {
client = alias
}
if a.ClientCalls == nil {
a.ClientCalls = make(map[string]map[int64]int64)
}
Expand Down
16 changes: 16 additions & 0 deletions internal/runtime/usage_aggregate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -554,3 +554,19 @@ func TestUsageAggregate_ClientCallsRetentionPreservesSupportedClients(t *testing
require.Equal(t, 1, agg.ClientCallsSince([]string{"cursor"}, base.Add(-24*time.Hour)))
require.LessOrEqual(t, len(agg.ClientCalls), 32)
}

func TestUsageAggregate_ClientCallsCreditBridgedKnownClient(t *testing.T) {
base := time.Date(2026, 10, 29, 12, 0, 0, 0, time.UTC)
agg := newUsageAggregate()
for _, client := range []string{"claude-ai (via mcp-remote 0.15.2)", "claude-ai (via mcp-remote 0.15.1)", "codex-mcp-client", "zed (via mcp-remote 0.15.2)"} {
agg.Apply(&storage.ActivityRecord{
Type: storage.ActivityTypeToolCall, ServerName: "github", ToolName: "search",
Status: storage.ActivityStatusSuccess, Timestamp: base,
Metadata: map[string]interface{}{"client_name": client},
})
}
since := base.Add(-24 * time.Hour)
require.Equal(t, 2, agg.ClientCallsSince([]string{"claude-ai", "Claude"}, since))
require.Equal(t, 1, agg.ClientCallsSince([]string{"codex", "codex-cli", "codex-mcp-client"}, since))
require.Equal(t, 1, agg.ClientCallsSince([]string{"zed (via mcp-remote 0.15.2)"}, since), "an unknown bridged client keeps its exact key")
}
7 changes: 6 additions & 1 deletion internal/telemetry/activation.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import (
"time"

"go.etcd.io/bbolt"

"github.com/smart-mcp-proxy/mcpproxy-go/internal/clientidentity"
)

// ActivationBucketName is the BBolt bucket that stores retention activation
Expand Down Expand Up @@ -452,7 +454,10 @@ var clientNameRegex = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{0,63}$`)
//
// Valid names are lowercased and returned unchanged.
func sanitizeClientName(raw string) string {
trimmed := strings.TrimSpace(raw)
// A client behind the mcp-remote bridge reports as the client it bridges.
// AliasCandidate already trims the raw name; trimming its result again
// would drop a control that sat before the bridge tag.
trimmed := clientidentity.AliasCandidate(raw)
if trimmed == "" {
return "unknown"
}
Expand Down
22 changes: 14 additions & 8 deletions internal/telemetry/activation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -258,14 +258,20 @@ func TestSanitizeClientName(t *testing.T) {
}{
{"claude-code", "claude-code"},
{"cursor", "cursor"},
{"Windsurf", "windsurf"}, // lowercased
{"", "unknown"}, // empty
{"/Users/alice/bin", "unknown"}, // path
{"C:\\Users\\bob", "unknown"}, // windows path
{"../relative", "unknown"}, // relative traversal
{"user@host", "unknown"}, // email-like
{"a.b.c_d-2", "a.b.c_d-2"}, // allowed chars
{"toolong" + longString(64), "unknown"}, // too long (>64)
{"Windsurf", "windsurf"}, // lowercased
{"", "unknown"}, // empty
{"/Users/alice/bin", "unknown"}, // path
{"C:\\Users\\bob", "unknown"}, // windows path
{"../relative", "unknown"}, // relative traversal
{"user@host", "unknown"}, // email-like
{"a.b.c_d-2", "a.b.c_d-2"}, // allowed chars
{"toolong" + longString(64), "unknown"}, // too long (>64)
{"claude-ai (via mcp-remote 0.15.2)", "claude-ai"}, // bridged client (GH #1786)
{"user@host (via mcp-remote 0.15.2)", "unknown"}, // bridge tag does not launder a bad name
{"claude-ai\n(via mcp-remote 0.15.2)", "unknown"}, // control separator is not a bridge tag
{"claude-ai\t (via mcp-remote 0.15.2)", "unknown"}, // control before the tag survives stripping
{"claude-ai\n (via mcp-remote 0.15.2)", "unknown"},
{"claude-ai\r (via mcp-remote 0.15.2)", "unknown"},
}
for _, tc := range cases {
got := sanitizeClientName(tc.in)
Expand Down
Loading