Skip to content

feat(sdk): expose server discovery - #1559

Merged
samuv merged 2 commits into
mainfrom
impl/sdk-server-discovery
Sep 15, 2026
Merged

samuv merged 2 commits into
mainfrom
impl/sdk-server-discovery

Conversation

@samuv

@samuv samuv commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Add the typed pre-session client.server namespace for compatibility and safe server identity.
  • Share race-safe compatibility generations while keeping the universal raw-client floor limited to API-major negotiation.
  • Validate strict server projections lazily for server.compatibility() and server.info() without coupling unrelated SDK operations to optional projection fields.
  • Add API reports, cross-language registry and deployment-bound parity, focused user documentation, and acceptance proofs.

Development stage

  • Plan / Interface
  • Implementation
  • Combined
  • Spike / Routine

Contract linkage

Interface conformance

  • Interfaces match approved contract: Yes.
  • No protobuf/generated-protobuf, exported Go, engine, tool-schema, CLI/config, event/persistence, or SDK changelog interface drift.
  • The implementation uses the existing GetCompatibilityInfo, GetServerInfo, and HTTP peer contracts.

Review fixes

  • Decouple API-major compatibility gating from strict optional-field projection, so malformed optional discovery data cannot fail unrelated raw or high-level operations.
  • Remove the raw.ts runtime dependency on the server namespace.
  • Reject a trailing unpaired high surrogate correctly.
  • Pin the TypeScript deployment byte limit to Go's 128-byte limit with a cross-language parity guard.
  • Preserve generation ordering: only a failed current projection can clear the shared cache; stale failures cannot evict newer state.

Issue relationship

Closes #1470

Test plan

  • task sdk:lint sdk:typecheck sdk:test sdk:build sdk:api:check (50 files, 276 tests)
  • task lint
  • task test
  • task docs
  • task site:build
  • go run ./cmd/mecademo
  • Targeted strict acceptance trace: 13 ACs, 0 failures

The whole-repository task ac-trace-strict currently stops on the unrelated pre-existing callmcpwithquery-broker-support.md status proposed. The equivalent targeted strict invocation passed:

go run github.com/stacklok/ac-trace/cmd/[email protected] --strict --plan docs/acceptance/sdk-server-discovery.md
13 ACs · 0 failure(s)

The directing user waived an additional post-repair panel rerun and requested that the verified fixes be pushed.

Changes

Area Change
sdk/typescript/src/server.ts Public server namespace, known values, validation, and detached projections
sdk/typescript/src/raw.ts API-major floor and shared race-safe raw compatibility generations
sdk/typescript/src/client.ts Lazy strict projection, generation-aware invalidation, and client.server wiring
SDK and Go tests Transport parity, cache races, validation boundaries, exports, and Go/TypeScript parity
User docs and API reports Focused server-discovery guide and generated public reference

User-facing change

Applications can inspect typed server compatibility, capabilities, features, posture, deployment identity, and safe build information before creating a session. Unknown open-string values remain observable, and gRPC/HTTP expose the same high-level behavior and typed failures.

Special notes for reviewers

  • llmProviderDisplayEndpoint is display-only diagnostic data, never connection configuration.
  • Every explicit server.compatibility() starts a fresh generation; ordinary operations share the newest generation.
  • buildId validation remains the approved trim-plus-nonempty contract.
  • Escaped-path cleaning remains aligned with Go rather than WHATWG URL.pathname semantics.
  • feat(sdk): generate release changelog entries #1482 owns generated SDK changelog entries, so this PR intentionally adds no manual changelog entry.

@kantord

kantord commented Sep 15, 2026

Copy link
Copy Markdown
Member

Panel review — PR #1559 (feat(sdk): expose server discovery)

Fully or partially written by an AI agent.

Fixed point: main (merge-base 1f44e781c)
Diff: 56 files, 2220 insertions, 184 deletions, 1 commit

Four orthogonal axes: Spec, Standards, Test adequacy, Domain (secure-code-reviewer, software-architect, library-reuse-reviewer, code-duplication-reviewer). Findings are not merged across axes.


Spec — does this implement what was asked?

Source: docs/acceptance/sdk-server-discovery.md (13 ACs across 4 scenarios)

No findings. All 13 ACs traced and confirmed against the implementation, including the trickier ones: generation-race semantics (AC2.1–2.3), the non-echo rule for rejected identity values (AC1.3/AC3.3), and cross-language registry parity (AC4.3). Nothing from the "Out of scope" table appears in the diff.


Standards — does this follow project conventions?

Sources read: ADR 0304, ADR 0248, ADR 0245, AGENTS.md

  • [advisory] The client-side deployment label bound (128 UTF-8 bytes) has no corresponding Go-side constant or cross-language parity test — unlike ServerFeature/ServerPosture, which get TestSDKServerDiscovery_Scenario4_ConstantRegistryParity. ADR 0248 established that parity-gate pattern precisely to prevent silent Go↔TS drift on open vocabularies; this one bound is left unguarded. Not blocking — it's a defensive client-side check that fails closed.
  • [advisory] The acceptance-plan status line says "landed" while also stating the Plan/Interface PR (docs: define SDK server discovery surface #1551) hasn't merged and neither PR is authorized to merge. Likely intentional per the stacked-PR workflow disclosed in the PR body, but worth a human sanity check against docs/development-process.md's plan-merge-as-approval gate before merge.

Test adequacy — do the tests independently prove the contract?

  • [important] AC3.3's "unsafe identity data never appears in a diagnostic record" claim is asserted via expect(diagnostics).toEqual([]) in server-discovery.test.ts, but tracing client.ts shows #emitDiagnostic is never called on this validation-failure path at all (#observeError doesn't call it, projectServerInfo/server.ts never touch the diagnostics sink). The array is empty by construction — the assertion can't catch a future regression that wires diagnostics into this path with an unredacted value. The .message/.cause/.toJSON() checks in the same test are genuine and adequate; only the diagnostics leg is untested against real leakage.

Everything else independently confirmed adequate: all 5 deployment-rejection rules tested independently, genuine Deferred-based race tests (not sequential awaits) for AC2.1/2.2, exhaustive per-rule endpoint-rejection coverage for AC3.3, real dual-transport parity test for AC4.1.


Domain — specialist findings

Panel: secure-code-reviewer, software-architect, library-reuse-reviewer, code-duplication-reviewer

Ship-blockers (1)

  • [blocker] The universal per-RPC compatibility gate now hard-fails on payload details no caller asked about.
    sdk/typescript/src/raw.ts:293,317 calls ensureCompatibility() unconditionally before every unary()/stream() call (session create, run, tool calls, spawn/watch readiness probes) — not just client.server.*. That call resolves through startCompatibility() → projectServerCompatibility() (raw.ts:250, server.ts), which now throws ProtocolError on an empty/duplicate features list, missing capabilities, or a malformed deployment label. Before this PR, features() read the raw unvalidated message; now a server quirk in a field nobody but client.server.compatibility() cares about (e.g. an operator-set deployment label with a stray control character) fails all SDK traffic, not just the new namespace. This directly contradicts ADR 0248's stated design goal — that open-string features tolerate partial/unusual deployments gracefully.
    Sources: software-architect (independently verified against the diff by the orchestrating session — confirmed at raw.ts:293/:317).
    Fix: decouple the shared pre-flight/features() path (keep it reading the raw, unvalidated message) from the strict ServerCompatibility value object; compute projectServerCompatibility lazily, only inside the client.server.compatibility()/info() call path.

Important (4)

  • [important] raw.ts now imports projectServerCompatibility/ServerCompatibility/SUPPORTED_API_MAJOR from server.ts, inverting the established dependency direction (namespace → raw, never raw → namespace; cf. session-projections.ts, which only the composition layer imports). Produces a type-level import cycle (raw.ts → server.ts → namespaces-core.ts → (type) raw.ts). Recommend extracting the projection helpers into a server-projections.ts sibling to session-projections.ts — this is also the natural fix once the blocker above makes validation lazy.
    Sources: software-architect
  • [important] ServerInfo.buildId skips the control-character/bounded/single-line validation applied to its sibling fields (deployment, serverImplementation) — only .trim() + nonempty. Since buildId crosses the same untrusted-server boundary and is documented (ADR 0245) as data applications display/log, an attacker-controlled value with embedded escape sequences or embedded newlines can manipulate a terminal (CWE-150) or forge log lines (CWE-117) — OWASP API10:2023 (Unsafe Consumption of APIs). AC3.2 does spec buildId as "trimmed and required nonempty" only, so this may be an accepted, deliberate decision — worth a one-line confirmation from whoever owns ADR 0245/0248 rather than treating the asymmetry as obviously intentional.
    Sources: secure-code-reviewer
  • [important, cross-confirmed] validUnicode() (server.ts) hand-rolls a ~10-line UTF-16 surrogate-pair scanner that reimplements String.prototype.isWellFormed() (native since Node 20 / ES2024 — within this SDK's engines.node: ">=22" floor). It also has a genuine bug: a string ending in an unpaired high surrogate is misclassified as valid (charCodeAt(index+1) returns NaN, and NaN < x/NaN > x are both false, so the rejection branch never fires — verified: validUnicode("\ud800") → true, should be false). Currently masked at both call sites (printableSingleLine's Unicode-category regex independently excludes surrogates; canonicalDiagnosticEndpoint's ASCII-only path/host requirements reject it another way), so not independently exploitable today — but it's reachable via JSON.parse on an HTTP transport (which doesn't enforce well-formed UTF-16), and any future reuse of validUnicode elsewhere loses the masking. Replacing the function with value.isWellFormed() removes ~10 lines and the bug in one move.
    Sources: library-reuse-reviewer, secure-code-reviewer
  • [important] cleanEscapedPath() hand-rolls dot-segment (./..) path normalization that duplicates what new URL() already does internally when parsing pathname — canonicalDiagnosticEndpoint already constructs a URL for scheme/userinfo/query/hash checks but doesn't reuse parsed.pathname for the traversal check, instead re-deriving normalization by hand. Two independently-maintained normalization algorithms for the same string is exactly the shape that produces silent drift (and here, potential path-traversal false-negatives). Comparing parsed.pathname !== path (the raw regex-captured path) would use the URL parser's own algorithm instead.
    Sources: library-reuse-reviewer

Advisory (2)

  • [advisory] sdk/typescript/test/server-discovery.test.ts's DiscoveryTransport mock is the 5th near-identical implements Transport boilerplate class across the test suite (Rule of Three long cleared). The mechanical boilerplate is genuinely mechanical; the per-test fixture logic that varies is what should stay divergent. Given 4 prior instances existed without the team extracting a shared factory, this looks like an accepted convention rather than an oversight — not worth acting on unless a 6th appears or the Transport interface shape changes.
    Sources: code-duplication-reviewer
  • [advisory] utf8Bytes() allocates a new TextEncoder() per call; hoisting one module-level instance would be marginally cleaner but has no correctness impact — not worth a standalone diff.
    Sources: library-reuse-reviewer

Gaps

  • (none — no reviewer errored or returned an unclassified finding)

Summary

  • Spec axis: 0 findings
  • Standards axis: 2 findings (0 blocker, 0 important, 2 advisory)
  • Test adequacy axis: 1 finding (0 blocker, 1 important, 0 advisory)
  • Domain axis: 1 blocker, 4 important (1 cross-confirmed), 2 advisory

Most important single issue: the compatibility-cache blocker — a malformed-but-harmless server response field can now fail every RPC on the client, not just the new client.server surface. This is the one finding that should block merge; everything else is a concrete, low-effort fix (the validUnicode/cleanEscapedPath stdlib swaps net ~-19 lines and also close the surrogate bug) or a judgment call to confirm with the ADR owner (buildId validation asymmetry).

PANEL: ship_blockers=1 important=5 advisory=4 reviewer_failures=0

@samuv

samuv commented Sep 15, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review — addressed in 9b3f2c1d6:

  • Decoupled the universal API-major compatibility floor from strict optional-field projection. Malformed optional discovery fields no longer fail unrelated raw/high-level operations, while server.compatibility() and server.info() still validate strictly.
  • Made projection-failure invalidation generation-aware, so a stale malformed generation cannot evict a newer pending or successful generation.
  • Removed the raw.ts runtime dependency on the server namespace.
  • Fixed trailing-unpaired-high-surrogate validation.
  • Added Go↔TypeScript parity for the 128-byte deployment bound.

I intentionally left three reviewed items unchanged:

  • buildId remains trim-plus-nonempty because that is the approved contract; strengthening it requires a plan amendment.
  • cleanEscapedPath remains because WHATWG URL.pathname normalization differs from Go escaped-path cleaning.
  • The diagnostics absence assertion remains valid for the approved non-observation guarantee.

Verification is green locally: all SDK gates (50 files, 276 tests), task lint, task test, docs/site builds, offline demo, and the targeted strict trace for all 13 ACs.

samuv and others added 2 commits September 15, 2026 18:44
Co-Authored-By: OpenAI Codex <[email protected]>
Signed-off-by: Samuele Verzi <[email protected]>
Signed-off-by: Samuele Verzi <[email protected]>
Co-Authored-By: OpenAI Codex <[email protected]>
@samuv
samuv force-pushed the impl/sdk-server-discovery branch from 9b3f2c1 to d6522d9 Compare September 15, 2026 16:44
@samuv
samuv merged commit f21089b into main Sep 15, 2026
35 checks passed
@samuv
samuv deleted the impl/sdk-server-discovery branch September 15, 2026 16:55
jtenniswood added a commit that referenced this pull request Sep 15, 2026
Upstream released the TypeScript SDK v0.2.0 with `client.server.compatibility()`
and `client.server.info()` (#1559), which cover two of this branch's SDK
additions. Resolution: drop the branch's duplicate `client.compatibility()` /
`client.serverInfo()` in favour of upstream's namespace; keep
`session.controls(runId)` and the stdlib-JSON Timestamp/Duration decoding;
regenerate the API reports and reference docs; point Studio's compatibility
and About-daemon readers at `client.server.*` (whose stricter validation the
Studio test fixtures now honour). Studio's ADRs move to 0345/0346 to clear
the number upstream took for 0343.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@toolhive-release-app toolhive-release-app Bot mentioned this pull request Sep 21, 2026
2 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SDK: expose compatibility, capabilities, and server information

2 participants