Skip to content

Commit a8adffc

Browse files
Dumbrisclaude
andauthored
fix(clients): credit mcp-remote-bridged Claude Desktop and codex-mcp-client sessions (#1799)
## Summary Codex CLI and Claude Desktop stayed `connected_never_seen` after Connect, and their sessions landed in `other:` rows (one per mcp-remote version), because presence matched `clientInfo.name` exactly against `ClientInfoNames`: - Codex CLI sends `codex-mcp-client`, which was not a Codex alias. - Claude Desktop through the mcp-remote bridge Connect writes sends `claude-ai (via mcp-remote <version>)`. ## Changes - `clientidentity.AliasCandidate`: `NormalizeRaw` plus removal of one trailing ` (via mcp-remote <version>)` tag. Strict grammar (single spaces, printable parenthesis-free version), and controls are preserved, so an escape- or newline-bearing name still cannot pass as a supported client. Used only for supported-alias lookup; unknown names keep their exact key. - Applied at every alias match site: `runtime.sanitizeClientName` (presence `ClientLastSeen`), `UsageAggregate.applyClientCalls` (24h calls), httpapi Clients hub (`clientMatches`, session `other:` check), and telemetry activation's client-name sanitizer. - Codex gains the `codex-mcp-client` alias. ## Not in scope - Pre-upgrade evidence recorded under the bridged name (`other:claude-ai (via mcp-remote 0.15.x)` rows, usage buckets) is not migrated; it stays as-is and ages out. New sessions are credited correctly. - `local-agent-mode-mcpproxy (via mcp-remote …)` and mcp-remote's `mcp-remote-fallback-test` probe still appear as `other:` rows (optional in the issue). ## Testing - New failing-first tests: `AliasCandidate` table incl. adversarial control/whitespace cases; `RecordClientSeen` for bridged + Codex names; usage aggregate crediting; Clients hub end-to-end (`claude-desktop`/`codex` rows get `last_seen` and the active session, no `other:` rows); escape-prefixed bridged name stays unknown; telemetry sanitizer cases. - `go test -race` for clientidentity, connect, runtime, telemetry, httpapi (CI skip regex): pass. - `./scripts/test-api-e2e.sh`: 70/70. - golangci-lint v2 (`.github/.golangci.yml`, bare and `--build-tags server`): no new findings. - Cross-model review: opencode `gpt-6.1-sol` + Claude Opus adversarial reviewer, 3 rounds; round 3 CLEAN. Closes #1786 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent dfa2b83 commit a8adffc

11 files changed

Lines changed: 176 additions & 21 deletions

‎internal/clientidentity/client_identity.go‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ package clientidentity
55
import (
66
"crypto/sha256"
77
"encoding/hex"
8+
"regexp"
89
"strings"
910
)
1011

@@ -127,6 +128,24 @@ func NormalizeRaw(raw string) string {
127128
return strings.ToLower(strings.TrimSpace(raw))
128129
}
129130

131+
// mcpRemoteSuffix matches the " (via mcp-remote <version>)" tag mcp-remote
132+
// appends to the clientInfo.name of the client it bridges (GH #1786). The
133+
// separators are single spaces and the version is printable ASCII without
134+
// parentheses, so a tag carrying a control character never matches.
135+
var mcpRemoteSuffix = regexp.MustCompile(`^(.*[^ ]) \(via mcp-remote(?: [!-'*-~]+)?\)$`)
136+
137+
// AliasCandidate is NormalizeRaw with one trailing mcp-remote bridge tag
138+
// removed, so "claude-ai (via mcp-remote 0.15.2)" classifies as the client
139+
// behind the bridge. Use it only to look up supported aliases: like
140+
// NormalizeRaw it preserves controls, and unknown names keep their exact key.
141+
func AliasCandidate(raw string) string {
142+
normalized := NormalizeRaw(raw)
143+
if m := mcpRemoteSuffix.FindStringSubmatch(normalized); m != nil {
144+
return m[1]
145+
}
146+
return normalized
147+
}
148+
130149
// SanitizeDisplay keeps rendered names safe and bounded.
131150
func SanitizeDisplay(raw string) string {
132151
var b strings.Builder

‎internal/clientidentity/client_identity_test.go‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,3 +22,35 @@ func TestFromRawKeepsTransformedAndFormerSuffixLookalikeDistinct(t *testing.T) {
2222
require.Equal(t, "~p:"+transformed.PublicID, sentinelLookalike.PublicID)
2323
require.NotEqual(t, transformedWithSentinelDisplay.PublicID, sentinelDisplayLookalike.PublicID, "a transformed display beginning with the sentinel must not recreate an escaped ordinary ID")
2424
}
25+
26+
func TestAliasCandidateStripsOneMCPRemoteBridgeSuffix(t *testing.T) {
27+
cases := map[string]string{
28+
"claude-ai (via mcp-remote 0.15.2)": "claude-ai",
29+
" Claude-AI (via mcp-remote 0.1.29) ": "claude-ai",
30+
"claude-ai (via mcp-remote)": "claude-ai",
31+
"codex-mcp-client": "codex-mcp-client",
32+
"Cursor": "cursor",
33+
"claude-ai (via something-else 1.0)": "claude-ai (via something-else 1.0)",
34+
"claude-ai (via mcp-remote 1) (via mcp-remote 2)": "claude-ai (via mcp-remote 1)",
35+
"(via mcp-remote 0.15.2)": "(via mcp-remote 0.15.2)",
36+
"claude-ai(via mcp-remote 0.15.2)": "claude-ai(via mcp-remote 0.15.2)",
37+
"claude-ai (via mcp-remote 0.15.2) x": "claude-ai (via mcp-remote 0.15.2) x",
38+
}
39+
for raw, want := range cases {
40+
require.Equal(t, want, AliasCandidate(raw), raw)
41+
}
42+
// Controls survive, so an escape-prefixed bridged name cannot pass as a
43+
// supported alias once the suffix is removed.
44+
require.Equal(t, "\x1bclaude-ai", AliasCandidate("\x1bclaude-ai (via mcp-remote 0.15.2)"))
45+
for _, raw := range []string{
46+
"claude-ai\n(via mcp-remote 0.15.2)",
47+
"claude-ai\t(via mcp-remote 0.15.2)",
48+
"claude-ai (via mcp-remote 0.15.2)",
49+
"claude-ai (via mcp-remote \x00)",
50+
"claude-ai (via mcp-remote 0.15\x1b2)",
51+
"claude-ai (via mcp-remote 0.15.2\n)",
52+
"claude-ai (via mcp-remote 0.15.2)",
53+
} {
54+
require.Equal(t, NormalizeRaw(raw), AliasCandidate(raw), "%q must not strip to a supported alias", raw)
55+
}
56+
}

‎internal/connect/clients.go‎

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,9 @@ var allClients = []ClientDef{
7070
Bridge: true,
7171
Icon: "claude-desktop",
7272
// "claude-ai" is Anthropic's published clientInfo.name for the Claude
73-
// Desktop app's MCP client.
73+
// Desktop app's MCP client. Through the mcp-remote bridge Connect
74+
// writes, it arrives as "claude-ai (via mcp-remote <version>)";
75+
// clientidentity.AliasCandidate strips that tag before matching.
7476
ClientInfoNames: []string{"claude-ai", "Claude"},
7577
ReloadHint: "Restart Claude Desktop to load MCPProxy",
7678
},
@@ -105,13 +107,14 @@ var allClients = []ClientDef{
105107
ReloadHint: "Run \"MCP: List Servers\" → Restart (or reload the window) in VS Code to load MCPProxy",
106108
},
107109
{
108-
ID: "codex",
109-
Name: "Codex CLI",
110-
Format: "toml",
111-
ServerKey: "mcp_servers",
112-
Supported: true,
113-
Icon: "codex",
114-
ClientInfoNames: []string{"codex", "codex-cli"},
110+
ID: "codex",
111+
Name: "Codex CLI",
112+
Format: "toml",
113+
ServerKey: "mcp_servers",
114+
Supported: true,
115+
Icon: "codex",
116+
// Codex CLI's rmcp client sends "codex-mcp-client" (GH #1786).
117+
ClientInfoNames: []string{"codex", "codex-cli", "codex-mcp-client"},
115118
ReloadHint: "Restart Codex CLI to load MCPProxy",
116119
},
117120
{

‎internal/httpapi/clients.go‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -568,7 +568,7 @@ func (s *Server) clientPresence(withSessions bool, detailID string) ([]clientPre
568568
}
569569
for _, session := range sessions {
570570
identity := clientidentity.FromRaw(session.ClientName)
571-
if identity.Key == "" || known[identity.RawNormalized] {
571+
if identity.Key == "" || known[clientidentity.AliasCandidate(session.ClientName)] {
572572
continue
573573
}
574574
id := "other:" + identity.PublicID
@@ -635,8 +635,9 @@ func latestClientSeen(seen map[string]time.Time, aliases []string) *time.Time {
635635
return &latest
636636
}
637637
func clientMatches(name string, aliases []string) bool {
638+
candidate := clientidentity.AliasCandidate(name)
638639
for _, alias := range aliases {
639-
if strings.EqualFold(strings.TrimSpace(name), alias) {
640+
if candidate == clientidentity.NormalizeRaw(alias) {
640641
return true
641642
}
642643
}

‎internal/httpapi/clients_presence_test.go‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -516,3 +516,54 @@ func successData(t *testing.T, rec *httptest.ResponseRecorder) map[string]any {
516516
require.True(t, envelope.Success)
517517
return envelope.Data
518518
}
519+
520+
func TestClientsPresence_CreditsBridgedClaudeDesktopAndCodex(t *testing.T) {
521+
rt, err := proxyRuntime.New(&config.Config{DataDir: t.TempDir(), Listen: "127.0.0.1:0"}, "", zap.NewNop())
522+
require.NoError(t, err)
523+
t.Cleanup(func() { require.NoError(t, rt.Close()) })
524+
525+
rt.RecordClientSeen("claude-ai (via mcp-remote 0.15.2)")
526+
rt.RecordClientSeen("codex-mcp-client")
527+
state, err := rt.GetOnboardingState()
528+
require.NoError(t, err)
529+
ctrl := &clientPresenceController{state: state, sessions: []*contracts.MCPSession{
530+
{ID: "desktop", ClientName: "claude-ai (via mcp-remote 0.15.2)", Status: "active", StartTime: time.Now().Add(-time.Minute), LastActivity: time.Now()},
531+
{ID: "codex", ClientName: "codex-mcp-client", Status: "active", StartTime: time.Now().Add(-time.Minute), LastActivity: time.Now()},
532+
}}
533+
srv := NewServer(ctrl, zap.NewNop().Sugar(), nil)
534+
req := httptest.NewRequest(http.MethodGet, "/api/v1/clients", nil)
535+
req.Header.Set("X-API-Key", "clients-admin-key")
536+
rec := httptest.NewRecorder()
537+
srv.ServeHTTP(rec, req)
538+
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
539+
540+
rows := map[string]map[string]any{}
541+
for _, raw := range successData(t, rec)["clients"].([]any) {
542+
row := raw.(map[string]any)
543+
require.NotEqual(t, "other", row["kind"], "bridged and Codex sessions must not become other: rows: %v", row["id"])
544+
rows[row["id"].(string)] = row
545+
}
546+
for _, id := range []string{"claude-desktop", "codex"} {
547+
require.Contains(t, rows, id)
548+
require.NotNil(t, rows[id]["last_seen"], id)
549+
require.Equal(t, float64(1), rows[id]["active_sessions"], id)
550+
}
551+
}
552+
553+
func TestClientsPresence_EscapePrefixedBridgedAliasRemainsOtherClient(t *testing.T) {
554+
ctrl := &clientPresenceController{sessions: []*contracts.MCPSession{{
555+
ID: "escaped", ClientName: "\x1bclaude-ai (via mcp-remote 0.15.2)", Status: "active", StartTime: time.Now().Add(-time.Minute), LastActivity: time.Now(),
556+
}}}
557+
srv := NewServer(ctrl, zap.NewNop().Sugar(), nil)
558+
req := httptest.NewRequest(http.MethodGet, "/api/v1/clients", nil)
559+
req.Header.Set("X-API-Key", "clients-admin-key")
560+
rec := httptest.NewRecorder()
561+
srv.ServeHTTP(rec, req)
562+
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
563+
for _, raw := range successData(t, rec)["clients"].([]any) {
564+
row := raw.(map[string]any)
565+
if row["id"] == "claude-desktop" {
566+
require.Equal(t, float64(0), row["active_sessions"], "escaped name must not credit Claude Desktop")
567+
}
568+
}
569+
}

‎internal/runtime/clients_presence_generation_test.go‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,3 +55,21 @@ func TestRecordClientSeenCapsOtherNamesWithoutEvictingKnownAliases(t *testing.T)
5555
require.LessOrEqual(t, len(state.ClientLastSeen), 32)
5656
require.Contains(t, state.ClientLastSeen, "cursor")
5757
}
58+
59+
func TestRecordClientSeenCreditsBridgedAndCodexClientNames(t *testing.T) {
60+
mgr, err := storage.NewManager(t.TempDir(), zap.NewNop().Sugar())
61+
require.NoError(t, err)
62+
t.Cleanup(func() { _ = mgr.Close() })
63+
r := &Runtime{storageManager: mgr, logger: zap.NewNop()}
64+
r.RecordClientSeen("claude-ai (via mcp-remote 0.15.2)")
65+
r.RecordClientSeen("codex-mcp-client")
66+
r.RecordClientSeen("\x1bclaude-ai (via mcp-remote 0.15.2)")
67+
68+
state, err := mgr.GetOnboardingState()
69+
require.NoError(t, err)
70+
require.Contains(t, state.ClientLastSeen, "claude-ai")
71+
require.Contains(t, state.ClientLastSeen, "codex-mcp-client")
72+
require.NotNil(t, latestSeenForAliases(state.ClientLastSeen, []string{"claude-ai", "Claude"}))
73+
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")
74+
require.Len(t, state.ClientLastSeen, 3, "the escape-prefixed name stays a distinct unknown client")
75+
}

‎internal/runtime/runtime.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4567,8 +4567,8 @@ func sanitizeClientName(raw string) string {
45674567
if identity.Key == "" {
45684568
return ""
45694569
}
4570-
if isKnownClientAlias(identity.RawNormalized) {
4571-
return identity.RawNormalized
4570+
if alias := clientidentity.AliasCandidate(raw); isKnownClientAlias(alias) {
4571+
return alias
45724572
}
45734573
return identity.Key
45744574
}

‎internal/runtime/usage_aggregate.go‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package runtime
22

33
import (
4+
"github.com/smart-mcp-proxy/mcpproxy-go/internal/clientidentity"
45
"math"
56
"sort"
67
"strings"
@@ -281,6 +282,9 @@ func (a *UsageAggregate) applyClientCalls(rec *storage.ActivityRecord) {
281282
if client == "" {
282283
return
283284
}
285+
if alias := clientidentity.AliasCandidate(raw); alias != client && knownClientAliases()[alias] {
286+
client = alias
287+
}
284288
if a.ClientCalls == nil {
285289
a.ClientCalls = make(map[string]map[int64]int64)
286290
}

‎internal/runtime/usage_aggregate_test.go‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -554,3 +554,19 @@ func TestUsageAggregate_ClientCallsRetentionPreservesSupportedClients(t *testing
554554
require.Equal(t, 1, agg.ClientCallsSince([]string{"cursor"}, base.Add(-24*time.Hour)))
555555
require.LessOrEqual(t, len(agg.ClientCalls), 32)
556556
}
557+
558+
func TestUsageAggregate_ClientCallsCreditBridgedKnownClient(t *testing.T) {
559+
base := time.Date(2026, 10, 29, 12, 0, 0, 0, time.UTC)
560+
agg := newUsageAggregate()
561+
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)"} {
562+
agg.Apply(&storage.ActivityRecord{
563+
Type: storage.ActivityTypeToolCall, ServerName: "github", ToolName: "search",
564+
Status: storage.ActivityStatusSuccess, Timestamp: base,
565+
Metadata: map[string]interface{}{"client_name": client},
566+
})
567+
}
568+
since := base.Add(-24 * time.Hour)
569+
require.Equal(t, 2, agg.ClientCallsSince([]string{"claude-ai", "Claude"}, since))
570+
require.Equal(t, 1, agg.ClientCallsSince([]string{"codex", "codex-cli", "codex-mcp-client"}, since))
571+
require.Equal(t, 1, agg.ClientCallsSince([]string{"zed (via mcp-remote 0.15.2)"}, since), "an unknown bridged client keeps its exact key")
572+
}

‎internal/telemetry/activation.go‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ import (
99
"time"
1010

1111
"go.etcd.io/bbolt"
12+
13+
"github.com/smart-mcp-proxy/mcpproxy-go/internal/clientidentity"
1214
)
1315

1416
// ActivationBucketName is the BBolt bucket that stores retention activation
@@ -452,7 +454,10 @@ var clientNameRegex = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{0,63}$`)
452454
//
453455
// Valid names are lowercased and returned unchanged.
454456
func sanitizeClientName(raw string) string {
455-
trimmed := strings.TrimSpace(raw)
457+
// A client behind the mcp-remote bridge reports as the client it bridges.
458+
// AliasCandidate already trims the raw name; trimming its result again
459+
// would drop a control that sat before the bridge tag.
460+
trimmed := clientidentity.AliasCandidate(raw)
456461
if trimmed == "" {
457462
return "unknown"
458463
}

0 commit comments

Comments
 (0)