1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
//! Bridge CUSTOM (non-native, non-builtin) MCP servers into a fleet session's
//! workspace `.mcp.json`, at USER and PROJECT scope (issue #2739 follow-up).
//!
//! Why: [`super::native_mcp`] closed the gap for the trusty-family NATIVE
//! allowlist only (`slack-mcp`, `telegram-mcp`, `gworkspace-mcp`,
//! `trusty-analyze`) — a deliberate, narrow first cut. Bob's follow-up
//! directive is broader: "support custom remote and local MCPs at a project or
//! user level", i.e. bridge servers that are NOT on that allowlist too, so an
//! operator-registered server like a Duetto HTTP endpoint reaches fleet
//! sessions the same way the native servers do. Two independent sources feed
//! this, each matching how trusty-mpm already models that scope:
//!
//! - **USER scope**: the SAME managed `.claude.json` `mcpServers` map
//! [`super::native_mcp`] reads (`tm mcp add`, see [`crate::core::mcp_config`]).
//! Any entry there that is NOT on the native allowlist and NOT one of the
//! three dedicated-injector builtins (`trusty-memory`/`trusty-search`/
//! `trusty-review`) is a "custom" user-scope server. The operator registered
//! it deliberately via `tm mcp add`, so bridging it into every fleet session
//! mirrors the native precedent — no new consent gate is needed for THIS
//! half.
//! - **PROJECT scope**: `<project>/.trusty-mpm/manifest.toml`'s `[mcp.custom]`
//! table — trusty-mpm's ALREADY-established per-project override file (see
//! `core::manifest`; the same layer `[agents]`/`[skills]` use), resolved with
//! the manifest's existing project > user > catalog > default precedence.
//! `session_launch::mod::prepare_session_inner` threads the resolved
//! `plan.custom_mcp_servers` in here.
//!
//! **Precedence when a name exists at both scopes: PROJECT wins.** This
//! function applies the user-scope registry FIRST, then the project-scope
//! manifest table SECOND — [`super::settings::inject_mcp_server`] is an
//! upsert-by-name, so a project entry silently overwrites a same-named user
//! entry. This is deliberate: a project's own declared MCP requirements are
//! more specific than the operator's blanket user registry, matching HR-2's
//! established "project override > user config" precedence used everywhere
//! else in the manifest.
//!
//! **Security decision (flagged for owner review, not guessed silently):**
//! bridging a REMOTE (http/sse) server is a real trust-surface expansion — the
//! URL/headers of a remote endpoint can carry a live credential (empirically
//! confirmed against the operator's own managed registry: an existing
//! `duetto-code-intelligence` entry carries its API key AS A URL QUERY
//! PARAMETER, not in `headers`). `.mcp.json` is git-TRACKED in real target
//! repos, so writing that verbatim would be the exact secret-leak class
//! [`super::native_mcp`] was built to prevent for stdio `env` — except a URL
//! has no structured "secret field" we can reliably strip the way `env`/
//! `headers` can be split out. This module's answer: [`validate_custom_remote_server`]
//! injects a remote entry ONLY when it carries NO `headers` (the clean-URL case
//! this issue's acceptance example — `duetto-memory` — is); an entry WITH
//! `headers` is REJECTED wholesale (fail-closed, `warn!`-logged), because there
//! is no established out-of-band delivery channel for an HTTP auth header
//! analogous to `.env.local` for stdio `env` today. A URL-embedded secret (the
//! `duetto-code-intelligence` shape) is NOT detected or stripped — there is no
//! reliable general way to do so without a false-negative that would still leak
//! it, so this is the ACTUAL open question flagged back to Bob: whether/how to
//! safely deliver a remote server's credential (URL- or header-borne) into a
//! git-tracked `.mcp.json`, e.g. via a documented `${VAR}`-expansion convention
//! Claude Code's own `.mcp.json` reader may support. Until that is decided, a
//! remote server that needs a credential (in the URL or in headers) simply does
//! not bridge — the fail-closed default matches the native module's existing
//! posture. Custom STDIO servers carry no such gap: their `env` is routed to
//! `.env.local` via the SAME [`super::native_mcp::route_mcp_secrets_to_env_local`]
//! machinery natives use.
//!
//! What: [`inject_custom_trusty_mcps`] is the `prepare_session_inner` call
//! site. For each candidate entry it dispatches on the declared transport:
//! `stdio` (or a bare command/no `type`) goes through
//! [`super::native_mcp::split_public_and_secret_env`] (the SAME positive-field
//! validator/secret-splitter natives use — its rules are name-agnostic);
//! `http`/`sse` goes through [`validate_custom_remote_server`]. Collected `env`
//! secrets are merged into `.env.local` via the shared native helper. Runs
//! BEFORE `preseed_workspace_trust_home` (same ordering requirement as the
//! native injector) so injected names flow into `enabledMcpjsonServers` — EXCEPT
//! the names that came from the PROJECT manifest scope, which
//! [`inject_custom_trusty_mcps`] returns to the caller so they can be excluded
//! from that auto-approval pre-seed (see the "consent" paragraph below).
//! Test: `custom_mcp_tests.rs`.
//!
//! **Reserved-name enforcement applies to BOTH scopes.** A project manifest
//! `[mcp.custom]` entry named e.g. `trusty-memory` or `slack-mcp` must be
//! rejected exactly like a same-named user-scope registry entry would be —
//! [`inject_mcp_server`] is an upsert-by-name and the dedicated/native
//! injectors for those reserved names run BEFORE this one
//! (`session_launch/mod.rs`), so an unfiltered project loop could silently
//! clobber a legitimate entry (arbitrary command execution via a spoofed
//! stdio command, or redirecting `trusty-memory`/`trusty-search` calls to an
//! attacker-controlled endpoint). Both scope loops call [`is_reserved_name`]
//! before injecting.
//!
//! **Name charset enforcement (issue #3033, MEDIUM finding 1).**
//! [`is_reserved_name`]'s exact-string comparison does NOT catch a
//! case-variant (`Trusty-Memory`) or Unicode-confusable (a non-ASCII hyphen in
//! place of ASCII `-`) typosquat of a reserved name — either shape sails past
//! it untouched. [`inject_one_custom_entry`] additionally requires every
//! candidate name (both scopes, since both loops route through it) to match
//! `^[a-z0-9][a-z0-9-]*$` via [`is_valid_custom_mcp_name`], rejecting the
//! typosquat class wholesale rather than chasing individual confusables.
//! Test: `custom_project_scope_rejects_case_variant_of_reserved_name`,
//! `custom_project_scope_rejects_unicode_hyphen_variant_of_reserved_name`,
//! `custom_project_scope_accepts_valid_lowercase_hyphen_name`.
//!
//! **Consent gate for project-scope servers.** A project-scope `[mcp.custom]`
//! entry ships with the CLONED REPO itself — unlike a user-scope registry
//! entry, which the operator personally added via `tm mcp add` on their OWN
//! machine. The PRIMARY safeguard (owner decision, superseding the original
//! interim design) is [`crate::core::project_trust::is_project_trusted`]:
//! [`inject_custom_trusty_mcps`] consults it before honoring ANY entry in
//! `project_custom` and, when the project is untrusted, skips the ENTIRE
//! project-scope loop with a single `warn!` naming the project path and
//! hinting `tm project trust <path>` (never logging entry values). Trust is
//! recorded in USER-scope state (`core::project_trust`, under
//! `~/.trusty-tools/trusty-mpm/`), never inside the repo, so a cloned repo
//! cannot self-trust; `tm project trust` / `tm project trust --revoke`
//! (`bin/tm/commands/project.rs`) are the only way to flip it. As
//! DEFENSE-IN-DEPTH this module additionally keeps the earlier no-preseed
//! safeguard: even for a TRUSTED project, [`inject_custom_trusty_mcps`]
//! returns the set of names it injected from the PROJECT scope so the caller
//! ([`super::settings::preseed_workspace_trust_home`]) can exclude them from
//! the `enabledMcpjsonServers` auto-approval — the server still bridges into
//! `.mcp.json` once trusted, but Claude Code's own "new MCP servers found"
//! consent dialog still fires for it in-session rather than being silently
//! pre-enabled. This is a deliberate simplification, not an oversight: it
//! costs the operator one extra in-session click even after explicitly
//! trusting the project, in exchange for never having to reason about a
//! separate "trusted AND pre-approved" code path. User-scope registry names
//! are unaffected by either gate (still pre-approved, matching the existing
//! native-allowlist posture) — the operator already consented to those by
//! registering them locally.
//! Test: `custom_project_scope_cannot_override_reserved_name`,
//! `custom_project_scope_cannot_override_trusty_memory`,
//! `custom_project_scope_cannot_override_trusty_search`,
//! `custom_project_scope_cannot_override_slack_mcp`,
//! `custom_project_scope_skipped_when_project_untrusted`,
//! `custom_project_scope_bridges_when_project_trusted`,
//! `custom_project_scope_skipped_again_after_revoke`.
//!
//! **Known limitation — no pruning of stale bridged entries (tracked in
//! issue #3045).** Once a custom server (user- or project-scope) is injected
//! into a workspace's `.mcp.json`, nothing ever removes it again if the
//! registry entry or manifest declaration is later revoked or deleted —
//! every past bridge target accumulates in `.mcp.json` forever, growing the
//! trust surface over time. A tracked-name-set approach (recording which
//! names THIS module injected, then pruning any that no longer appear in
//! either source on the next `prepare_session`) would close this, but is
//! deliberately NOT implemented here; see issue #3045 and the CHANGELOG
//! entry for this change.
use ;
use Path;
use Value;
use PrepError;
use ;
use inject_mcp_server;
use crateCustomMcpServer;
use crate;
use crateis_project_trusted;
use cratemanaged_claude_config_dir;
/// The ONLY top-level fields a custom remote (http/sse) registration may carry
/// for [`validate_custom_remote_server`] to accept it.
///
/// Why: mirrors [`super::native_mcp`]'s positive-field-allowlist philosophy —
/// enumerate what IS safe rather than blocklist what isn't, so a new
/// secret-bearing field invented upstream fails closed by default.
/// What: `type`, `url`. `headers` is deliberately EXCLUDED from the injectable
/// set (see the module docs' security-decision section) — a registration
/// carrying `headers` is rejected wholesale rather than having `headers`
/// silently dropped, so the operator can see (via the `warn!`) exactly why
/// their server did not bridge.
const INJECTABLE_REMOTE_FIELDS: & = &;
/// Bridge CUSTOM (non-native, non-builtin) MCP servers from BOTH the
/// user-scope managed registry and the resolved project-scope manifest table
/// into the workspace `.mcp.json` (issue #2739 follow-up).
///
/// Why: this is the `prepare_session_inner` call site, run alongside (and
/// after) [`super::native_mcp::inject_native_trusty_mcps`] so the native
/// allowlist and the broader custom set are both bridged before trust preseed.
/// What: reads the managed `.claude.json` registry (best-effort — a
/// stripped-environment or read failure is logged and treated as "no user-scope
/// entries", never fatal to the launch) and injects every entry that is not a
/// native or builtin reserved name. THEN, only when
/// [`crate::core::project_trust::is_project_trusted`] returns `true` for
/// `project_path`, injects every entry in `project_custom` (overwriting a
/// same-named user entry — see the module docs for the precedence rationale).
/// An untrusted project's `project_custom` table is skipped in its entirety
/// (logged once at `warn!`, never fatal). Collected stdio secrets are merged
/// into `.env.local` once at the end. Non-fatal: an injection or
/// secret-routing failure for one entry never aborts the rest.
///
/// Returns the set of names actually injected from the PROJECT scope (not the
/// user scope) so the caller can exclude them from the workspace-trust
/// auto-approval pre-seed (see the module docs' "Consent gate" section) —
/// only names for which [`inject_one_custom_entry`] actually wrote an entry
/// are included, so a project-scope entry that itself fails validation (e.g.
/// a headers-bearing remote server) is never wrongly excluded from
/// pre-approval when it left a pre-existing user-scope entry of the same name
/// untouched. Always empty when the project is untrusted.
/// Test: `custom_user_scope_http_server_bridges`,
/// `custom_user_scope_stdio_server_bridges_with_secret_routing`,
/// `custom_project_scope_server_bridges`,
/// `custom_project_scope_overrides_user_scope_on_name_collision`,
/// `custom_bridging_skips_native_and_builtin_names`,
/// `custom_project_scope_cannot_override_reserved_name`,
/// `custom_project_scope_cannot_override_trusty_memory`,
/// `custom_project_scope_cannot_override_trusty_search`,
/// `custom_project_scope_cannot_override_slack_mcp`,
/// `custom_project_scope_skipped_when_project_untrusted`,
/// `custom_project_scope_bridges_when_project_trusted`,
/// `custom_project_scope_skipped_again_after_revoke`,
/// `custom_project_scope_rejects_case_variant_of_reserved_name`,
/// `custom_project_scope_rejects_unicode_hyphen_variant_of_reserved_name`,
/// `custom_project_scope_accepts_valid_lowercase_hyphen_name`.
pub
/// Whether `name` is already owned by another injector and must never be
/// treated as a "custom" server here.
///
/// Why: the native allowlist has its own injector
/// ([`super::native_mcp::inject_native_trusty_mcps`]), and the three builtins
/// (`trusty-memory`/`trusty-search`/`trusty-review`) have their own dedicated,
/// pinning-aware injectors — re-injecting any of them here (unpinned, or
/// duplicated) would clobber that ownership.
/// What: `true` iff `name` is in [`NATIVE_TRUSTY_MCP_SERVERS`] or
/// [`BUILTIN_MANAGED_MCP_SERVERS`]. Applied identically to BOTH the
/// user-scope registry loop and the project-scope manifest loop in
/// [`inject_custom_trusty_mcps`] — a project manifest must not be able to
/// bypass this check the user-scope loop already enforced.
/// Test: `custom_bridging_skips_native_and_builtin_names`,
/// `custom_project_scope_cannot_override_reserved_name`,
/// `custom_project_scope_cannot_override_trusty_memory`,
/// `custom_project_scope_cannot_override_trusty_search`,
/// `custom_project_scope_cannot_override_slack_mcp`.
/// Whether `name` matches the strict custom-MCP-server charset
/// `^[a-z0-9][a-z0-9-]*$` (issue #3033, MEDIUM finding 1).
///
/// Why: [`is_reserved_name`] does an exact, case-sensitive, codepoint-exact
/// string comparison against the reserved-name tables — it does NOT catch a
/// case-variant (`Trusty-Memory`) or a Unicode confusable (a non-ASCII hyphen
/// U+2011 in place of ASCII `-`) typosquat of a reserved name. Either shape
/// sails past `is_reserved_name` untouched, then renders in a UI or log line
/// close enough to the real name to fool an operator. Restricting the
/// ENTIRE custom-server namespace to lowercase ASCII letters, digits, and
/// hyphens closes that typosquat class wholesale, independent of the
/// reserved-name table's exact contents.
/// What: `true` iff `name` is non-empty, its first character is an ASCII
/// lowercase letter or digit, and every subsequent character is an ASCII
/// lowercase letter, digit, or `-` (equivalent to the regex
/// `^[a-z0-9][a-z0-9-]*$`, checked without a `regex` dependency).
/// Test: `custom_project_scope_rejects_case_variant_of_reserved_name`,
/// `custom_project_scope_rejects_unicode_hyphen_variant_of_reserved_name`,
/// `custom_project_scope_accepts_valid_lowercase_hyphen_name`.
/// Validate and inject a single custom entry, dispatching on its declared
/// transport.
///
/// Why: branching on the declared `type` BEFORE validating (rather than trying
/// the stdio validator and falling back to the remote one) avoids a spurious
/// "not stdio" warning firing for every legitimate http/sse entry —
/// [`split_public_and_secret_env`] always logs on rejection, so calling it
/// speculatively against a remote entry would double-warn.
/// What: `http`/`sse` entries go through [`validate_custom_remote_server`];
/// everything else (`stdio`, or no `type` at all — the bare-command shape) goes
/// through [`split_public_and_secret_env`], with any `env` secrets folded into
/// `secret_env` for the caller to route. A rejected entry is simply not
/// injected (already `warn!`-logged by the validator). Returns `true` iff an
/// entry was actually written to `.mcp.json`, so callers (specifically the
/// project-scope loop in [`inject_custom_trusty_mcps`]) can track exactly
/// which names this call caused to appear, rather than which names were merely
/// attempted.
/// Test: covered via `inject_custom_trusty_mcps`'s own test suite.
/// Validate a custom remote (http/sse) registration and return its injectable
/// public shape, or `None` (logged) to reject.
///
/// Why (the module docs' security-decision section): a remote server's
/// credential may live in `headers` OR directly in the `url` itself — the
/// operator's own managed registry has a real example of the latter
/// (`duetto-code-intelligence`, an API key as a URL query parameter). There is
/// no safe out-of-band delivery channel for either today (unlike stdio `env`,
/// which routes to `.env.local`), so this fails closed on `headers` and
/// otherwise trusts the URL verbatim — the same posture the acceptance
/// example (`duetto-memory`, a clean URL with no headers) is designed to pass.
/// What: returns `Some({"type": <http|sse>, "url": <url>})` when `entry` is a
/// JSON object carrying ONLY fields in [`INJECTABLE_REMOTE_FIELDS`] (i.e. no
/// `headers` key at all — even an empty `headers: {}` is rejected, so an
/// operator who registered headers sees a consistent, unsurprising rejection
/// rather than a silent partial injection) and `url` is a non-empty string.
/// Any other shape (missing/blank `url`, a non-object entry, or any field
/// outside the allowlist) is rejected with a `warn!` explaining why.
/// Test: `remote_custom_server_without_headers_is_injected`,
/// `remote_custom_server_with_headers_is_rejected`,
/// `remote_custom_server_rejects_unknown_field`,
/// `remote_custom_server_rejects_missing_url`.
pub
/// Convert a project-manifest [`CustomMcpServer`] definition into the same
/// `.claude.json`-registry-entry JSON shape [`crate::core::mcp_config`]
/// produces, so [`inject_one_custom_entry`] can validate/inject it through the
/// exact same code path as a user-scope registry entry.
///
/// Why: keeping ONE validation/injection path (rather than a parallel one for
/// the manifest's typed enum) means the security rules in this module
/// (positive field allowlist, header rejection, secret routing) apply
/// identically no matter which scope a server came from.
/// What: `Stdio` → `{"type":"stdio","command":..,"args":[..],"env":{...}}`
/// (omitting `env` when empty, matching [`crate::core::mcp_config::build_stdio_entry`]);
/// `Http`/`Sse` → `{"type":<http|sse>,"url":..,"headers":{...}}` (omitting
/// `headers` when empty).
/// Test: `custom_project_scope_server_bridges` (stdio and http both, via the
/// end-to-end injector test).
/// Shared builder for the `Http`/`Sse` arms of [`custom_manifest_entry_to_value`].
///
/// Why: the two remote variants differ only in the `type` discriminant;
/// factoring the shape construction avoids duplicating it.
/// What: `{"type": <transport>, "url": <url>}`, adding `"headers": {<headers>}`
/// only when non-empty (the resulting value still flows through
/// [`validate_custom_remote_server`], which rejects any `headers`-bearing
/// entry — this builder does not itself enforce that policy).
/// Test: covered transitively by `custom_project_scope_server_bridges`.