LibreChat/packages/api
Danny Avila 29b3e2ef3e
📜 fix: Resolve MCP Server Instructions for Startup-Deferred Servers (#15361)
* fix: Fetch MCP Instructions from the First Live Connection

Startup inspection intentionally defers servers that need per-user or runtime context, including OAuth/OBO, custom variables, user API keys, runtime placeholders, and startup-disabled servers. An enabled serverInstructions declaration therefore never resolves to text during inspection, even though the first live connection already has the instructions from the initialize response.

Backfill resolvedInstructions from that connection through an identity-preserving YAML cache patch. Preserve updatedAt so live connections do not become stale, and globally invalidate the tenant-scoped read-through caches because YAML entries are shared across tenants. Literal instruction strings continue to win.

Scope remains YAML-tier servers. Config-overlay servers are keyed by config hash, and DB-backed user servers need a separate identity-preserving write through mongoose timestamps and credential sanitization.

* fix: Surface per-identity MCP instruction divergence

`resolvedInstructions` is a single field on a config shared by every user
of the server, and for a startup-deferred server the text now comes from
one user's authenticated connection. That is exact for a server
advertising one static block, but a server that tailors instructions per
identity cannot be represented by it.

Rather than let the stored copy churn per connection — each write
invalidates the read-through cache globally, and the model context would
vary by whoever connected last — keep the first text and log the
divergence, so the assumption is diagnosable instead of silent.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SxKWxwqxAGckYpRsYTqx3F

* perf: Skip MCP instruction backfill for non-YAML tiers

`setResolvedInstructions` writes only the YAML tier, so a config-overlay,
user, or plugin server reached it, spent a cache round-trip — a network
hop under Redis — and was refused. That repeated on every connection
creation, because the refusal leaves `resolvedInstructions` unset and
nothing memoizes the outcome.

Gate on the existing `isUserSourced`/`isPluginSourced` predicates plus an
explicit `config` check. An unset source still proceeds: it predates
per-tier stamping and the registry resolves it by name.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SxKWxwqxAGckYpRsYTqx3F

* test: Pin the MCP instruction context read path

Every existing assertion read back through `getServerConfig`, but
`MCPManager.getInstructions` resolves instructions from
`getAllServerConfigs`, which is served by a different read-through cache.
A backfill that invalidated only the per-server cache would pass the
suite and still leave the reported bug unfixed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SxKWxwqxAGckYpRsYTqx3F

* fix: Refuse MCP instruction backfill from mismatched configs

Self-review findings on the backfill, both in the shared-copy write:

A config-tier override shadowing a YAML base keeps the base's 'yaml'
source tag (`overlaySource`), so the connection manager's tier guard
cannot see it, and instructions fetched from a tenant's overridden
endpoint would be patched into the shared global YAML entry — reaching
every other tenant's model context and persisting after the override is
removed. `setResolvedInstructions` now takes the config the delivering
connection was created from and compares it field-wise against the
stored entry over ADMIN_CONFIGURABLE_FIELDS, refusing on mismatch.
Field-wise rather than whole-object, since inspector-derived fields
legitimately differ.

The skip condition also only refused *identical* text, so a connection
built from a stale read-through snapshot (resolvedInstructions still
unset) could overwrite already-stored different text — violating the
documented first-write-wins invariant and re-triggering global cache
invalidation per divergence. The condition is now `!= null`.

Documented the aggregate-key cross-instance write race alongside its
existing tolerance for `reinspectServer`: the backfill patch fires at
most once per server per registry lifetime, and the atomic-write
upgrade (hash fields or Lua CAS) is the follow-up that closes the
race for every writer at once.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SxKWxwqxAGckYpRsYTqx3F

* fix: Scope deferred MCP instructions safely

* fix: Narrow optional Keyv namespace in Redis store detection

Keyv types `namespace` as `string | undefined`, so passing it straight
into `FORCED_IN_MEMORY_CACHE_NAMESPACES?.includes(...)` fails
`tsc --noEmit` in both cache classes — tsdown builds do not catch it,
but the TypeScript type checks CI job runs tsc and would. An unset
namespace (never the case after construction) now reads as not
Redis-backed, which falls back to the guarded non-Lua path.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SxKWxwqxAGckYpRsYTqx3F

* fix: Harden the shared-instruction gate and CAS the patch

Codex round two, both verified before fixing:

A configured `oauth` block slips the backfill gate whenever
`requiresOAuth` is not literally true. The inspector stamps
`requiresOAuth = false` on every `startup: false` server without
consulting `oauth`, so the stamped population connects bare and fetches
anonymously — but the gate's safety rested entirely on that stamp: a
config reaching the manager unstamped gets OAuth machinery armed
(`isOAuthServer` treats `oauth != null` as OAuth) while
`requiresUserScopedConnection` waves it through. The gate now rejects
`oauth`/`oauth_headers` outright; genuinely static servers carry
neither.

The registry validates config identity against a snapshot that can lag
by the cache TTL, while the Lua patch checked only that
`resolvedInstructions` was unset — so a replica could validate against
an old entry, another replica replace it, and the patch land
instructions on the replacement. `patch` now takes the validated
entry's `updatedAt` and both Lua scripts (and the in-memory and
fallback paths) refuse when the stored entry no longer matches:
identity validation and the write are one compare-and-set.

Both guards verified red-without-fix; suite 36/36.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SxKWxwqxAGckYpRsYTqx3F

* fix: Loosen apiKey on the scoping config and sort imports

CI caught two things local gates filtered past:

`UserScopedConnectionConfig` gained `apiKey` on the strict Pick side,
but raw (pre-inspection) configs carry an optional `apiKey.source` —
exactly what the type's loosened intersection exists for — so
`agents/initialize.ts` stopped compiling. The gate only reads
`apiKey?.source`, so the loosened shape is sufficient and the
TypeScript type checks job goes green again.

The `canBackfillSharedServerInstructions` import landed unsorted in
UserConnectionManager.ts, failing the changed-file import-sort gate.

Verified with a full `tsc --noEmit` error-list diff against clean dev
(zero branch-only errors) rather than per-directory counts, which is
how the initialize.ts error slipped local verification.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SxKWxwqxAGckYpRsYTqx3F

* fix: Make MCP aggregate writes atomic

* test: Fix Redis aggregate spy assertion

* fix: Reject placeholder-bearing admin keys from shared backfill

Codex round three P1, verified end-to-end before fixing: processMCPEnv
injects an admin `apiKey.key` into the request headers (env.ts:448)
BEFORE header values get per-user placeholder resolution (env.ts:478),
so a key like `{{LIBRECHAT_OPENID_ACCESS_TOKEN}}` makes the connection
identity-scoped — while `placeholderBearingFields` never inspects
`apiKey.key` and the gate rejected only `source: 'user'`. Instructions
fetched under one user's identity could then be stored for everyone.

The gate now scans the admin key value with the same runtime-placeholder
predicate. Kept narrow deliberately: widening
`placeholderBearingFields` itself would change
`requiresUserScopedConnection` for every caller — connection pooling
included — which is its own decision.

Static admin keys still backfill (positive control test); both new
refusal tests verified red without the gate change. Suite 39/39.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SxKWxwqxAGckYpRsYTqx3F

* refactor: Drop gate term covered by placeholder-bearing apiKey

eb117d1b4 added `apiKey.key` to `placeholderBearingFields`, so
`requiresUserScopedConnection` now rejects placeholder-bearing admin
keys for every caller — connection pooling included — and the explicit
scan in `canBackfillSharedServerInstructions` from the rebased
32d598692 became a duplicate of that broader check. The refusal tests
stay green through the shared path alone, which also confirms the
broader mechanism covers the round-three finding.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SxKWxwqxAGckYpRsYTqx3F

* fix: Preserve empty arrays in Redis aggregate mutations

* fix: Scope env-expanded MCP placeholders

* test: Harden Redis empty-array preservation

* style: Fix Redis cache static checks

* test: Narrow Redis empty-array fixtures

---------

Co-authored-by: Simon Guldager <sg@nobly.dk>
Co-authored-by: Claude <noreply@anthropic.com>
2026-08-30 16:17:26 -04:00
..
src 📜 fix: Resolve MCP Server Instructions for Startup-Deferred Servers (#15361) 2026-08-30 16:17:26 -04:00
types
.gitignore
babel.config.cjs
jest.config.mjs 🔇 refactor: Quiet Framework Logging in Unit Tests (#15363) 2026-08-30 15:26:30 -04:00
jest.setup.cjs
package.json 🍵 feat: Continue Late Steers in Warm Agent Runs (#15357) 2026-08-30 11:54:17 -04:00
tsconfig-paths-bootstrap.mjs
tsconfig.build.json
tsconfig.json 🥸 chore: Resolve Agents SDK Path Aliases That Masked Backend Types (#15160) 2026-08-24 08:38:30 -04:00
tsconfig.spec.json
tsdown.config.mjs 🫆 chore: Remove Published Credential Defaults (#14680) 2026-08-07 07:25:05 -04:00