@goodtiming/baton-sdk 0.6.4 → 0.6.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -36,7 +36,7 @@ Copy the DSN from **/account**. It packs four values: the collector to send to,
36
36
 
37
37
  **Installing changes what your server advertises.** Each tool handler is wrapped, one sentence is added below your server's own `instructions`, and a `user_goal` parameter is added to every tool's schema and stripped again before your handler sees it. With `reportMode: "on"`, an annotation tool is also registered, named from your server's own name (slugged, `<server-name>_annotate`, so `your-vendor-mcp_annotate` here), and the added text tells the agent when to report a problem with it. [What gets injected](https://goodtiming.ai/docs.html#injected-tools).
38
38
 
39
- With no DSN and no sink, events go to `StdoutSink`, which writes to stderr, so a stdio server's stdout stays clean and nothing goes over the network.
39
+ With no DSN, no `vendorId`, no `tenantId` and no sink, `withBaton` warns once and installs nothing: your server starts as usual and nothing is recorded. A setting with a value that is not valid still throws, and so does a `tenantId` or sink without a `vendorId`. With a `vendorId` and no DSN or sink, events go to `StdoutSink`, which writes to stderr, so a stdio server's stdout stays clean and nothing goes over the network.
40
40
 
41
41
  **If you distribute your server, put the DSN in your source.** A stdio server runs on your user's machine, spawned by their MCP client. The official client SDKs pass it a fixed six-variable allowlist (`HOME`, `LOGNAME`, `PATH`, `SHELL`, `TERM`, `USER`), plus whatever that user wrote in their own client config. Nothing from your `.env` is in either list, so a server configured that way captures nothing while appearing to work.
42
42
 
@@ -66,7 +66,7 @@ Call `await baton.aclose()` in your own shutdown path, after the HTTP server sto
66
66
 
67
67
  What a stateless server costs, with either function:
68
68
 
69
- - **Every request is its own session.** The protocol gives a stateless server no session id, so the SDK does not invent a join between two requests. To see one person's requests together, return a principal from `resolvePrincipal` ([Who is calling](#who-is-calling)): the Console lists sessions by person. If your HTTP handler has already authenticated the request, hand the user to the hook as `authInfo`. On `@modelcontextprotocol/sdk` 1.x that is `req.auth`, shown here; on `@modelcontextprotocol/server` 2.x pass `{ authInfo }` when you hand the request to the transport:
69
+ - **Every request is its own session**, unless the client sends an `mcp-session-id` header: then its requests share that session, and `createBaton` numbers them in order across requests. Without one, a stateless server has no session id, and the SDK does not invent a join between two requests. To see one person's requests together, return a principal from `resolvePrincipal` ([Who is calling](#who-is-calling)): the Console lists sessions by person. If your HTTP handler has already authenticated the request, hand the user to the hook as `authInfo`. On `@modelcontextprotocol/sdk` 1.x that is `req.auth`, shown here; on `@modelcontextprotocol/server` 2.x pass `{ authInfo }` when you hand the request to the transport:
70
70
 
71
71
  ```js
72
72
  const baton = createBaton({
@@ -85,7 +85,7 @@ What a stateless server costs, with either function:
85
85
  });
86
86
  ```
87
87
 
88
- Signals that need several calls in one session, such as a retry loop, do not fire across requests.
88
+ Without that header, signals that need several calls in one session, such as a retry loop, do not fire across requests.
89
89
  - **The client is named from its `User-Agent`.** A client states its name in the `initialize` handshake, and a per-request server never sees the handshake of the call it is serving. Each event still carries the request's `User-Agent` header in `client_observed`, and your dashboard names the client from that.
90
90
 
91
91
  ## Without MCP: the library API
@@ -259,8 +259,9 @@ Checking it worked: `handle.sink` is still an object, so finding one there is no
259
259
  None of it blocks the quickstart above.
260
260
 
261
261
  - Only the high-level `McpServer`. The low-level `Server` is not wrapped.
262
- - **Task-based tools are not wrapped, and are not left alone either.** A 1.x tool registered with an object at `.handler` rather than a function produces no `tool_call_*` events at all, and nothing reports that. It still gets the intent parameters added to its advertised schema, because injection runs before the wrap is skipped and the strip only happens inside the wrapper. So `user_goal` can arrive in your own handler's arguments. Tools on the same server registered the ordinary way are unaffected. ⚠ **The request-level seam above does not rescue this one**: it reports only on tools this package wrapped, so a task-based tool emits nothing even for a rejected argument, where an unknown tool now emits a `tool_call_error`.
262
+ - **Task-based tools are not wrapped.** A 1.x tool registered with an object at `.handler` rather than a function produces no `tool_call_*` events at all, and nothing reports that. It still advertises `user_goal`, which Baton removes from the call before your handler sees it, wherever it can reach the server's `tools/call` handler. Tools on the same server registered the ordinary way are unaffected. ⚠ **The request-level seam above does not rescue this one**: it reports only on tools this package wrapped, so a task-based tool emits nothing even for a rejected argument, where an unknown tool now emits a `tool_call_error`.
263
263
  - Intent parameters need a Zod schema. On the 2.x SDK a tool registered with a non-Zod standard schema is still wrapped and still emits `tool_call_*`; it just advertises no intent parameters.
264
+ - `resources/templates/list` sends no events.
264
265
  - v2's `createMcpHandler` is tested only for calls that pause for input. A server built per request by your own code is supported: see [A server per request](#a-server-per-request).
265
266
 
266
267
  ## Wire compatibility
package/dist/index.cjs CHANGED
@@ -103,7 +103,7 @@ __export(index_exports, {
103
103
  module.exports = __toCommonJS(index_exports);
104
104
 
105
105
  // src/version.ts
106
- var SDK_VERSION = "ts-0.6.4";
106
+ var SDK_VERSION = "ts-0.6.5";
107
107
 
108
108
  // src/events.ts
109
109
  var import_zod = require("zod");
@@ -945,7 +945,8 @@ var HttpSink = class _HttpSink {
945
945
  reportedSum = 0;
946
946
  lastReportAt = -Infinity;
947
947
  reportsStopped = false;
948
- /** The envelope of a report due to ride the next batch, and when it was set up. */
948
+ /** The envelope of a report due to ride the next batch, and when it was set up.
949
+ * `built` is the report once taken: a kept batch resends it unchanged (SPEC §11.4.7). */
949
950
  pendingReport = null;
950
951
  reportSetAt = 0;
951
952
  constructor(url, options) {
@@ -1161,7 +1162,7 @@ var HttpSink = class _HttpSink {
1161
1162
  while (this.circuit.canRequest() && Date.now() >= this.retryAt && Date.now() < deadline) {
1162
1163
  const batch = this.takeBatch(false);
1163
1164
  if (batch === null) break;
1164
- if (!this.putBack(await this.sendBatch(batch, 0, deadline))) break;
1165
+ if (!this.putBack(await this.sendBatch(batch, 0, deadline), batch)) break;
1165
1166
  }
1166
1167
  this.exitPassRan = true;
1167
1168
  this.unsentWarned = true;
@@ -1248,7 +1249,7 @@ var HttpSink = class _HttpSink {
1248
1249
  const batch = this.takeBatch(reportDue);
1249
1250
  if (batch === null) break;
1250
1251
  if (batch.some((w) => w.reportSum !== void 0)) reportDue = false;
1251
- if (!this.putBack(await this.sendBatch(batch, this.maxRetries, Infinity))) {
1252
+ if (!this.putBack(await this.sendBatch(batch, this.maxRetries, Infinity), batch)) {
1252
1253
  failed = true;
1253
1254
  break;
1254
1255
  }
@@ -1279,19 +1280,20 @@ var HttpSink = class _HttpSink {
1279
1280
  }
1280
1281
  /** Takes the head of the buffer that fits one batch: one tenant and vendor
1281
1282
  * (SPEC §2.5), at most 100 events and 1 MiB. A due report with the head
1282
- * event's tenant and vendor takes one of those places; otherwise it is not
1283
- * built, and waits for a batch it can ride. Without a batch endpoint the same events go one
1284
- * per request. */
1283
+ * event's tenant and vendor takes one of those places, and goes alone when
1284
+ * the head event fits only without it. A report that cannot ride the head
1285
+ * waits for a batch it can ride. Without a batch endpoint the same events
1286
+ * go one per request. */
1285
1287
  takeBatch(withReport) {
1286
1288
  const batch = [];
1287
1289
  let bytes = BATCH_FRAME_BYTES - 1;
1288
1290
  let eventBytes = 0;
1289
- const fits = (w, maxEvents2 = BATCH_MAX_EVENTS, maxBytes2 = BATCH_MAX_BYTES) => batch.length === 0 || batch.length < maxEvents2 && sameBatch(w.event, batch[0].event) && bytes + 1 + w.bytes <= maxBytes2;
1290
- const report = withReport && this.reportRidesHead() ? this.buildReport() : null;
1291
+ const report = withReport && this.reportRidesHead() ? this.pendingReport.built ?? this.buildReport() : null;
1291
1292
  const maxEvents = BATCH_MAX_EVENTS - (report ? 1 : 0);
1292
1293
  const maxBytes = BATCH_MAX_BYTES - (report ? 1 + report.bytes : 0);
1294
+ const fits = (w) => bytes + 1 + w.bytes <= maxBytes && (batch.length === 0 || batch.length < maxEvents && sameBatch(w.event, batch[0].event));
1293
1295
  for (const waiting of this.buffer) {
1294
- if (!fits(waiting, maxEvents, maxBytes)) break;
1296
+ if (!fits(waiting)) break;
1295
1297
  batch.push(waiting);
1296
1298
  bytes += 1 + waiting.bytes;
1297
1299
  eventBytes += waiting.bytes;
@@ -1299,21 +1301,19 @@ var HttpSink = class _HttpSink {
1299
1301
  this.buffer.splice(0, batch.length);
1300
1302
  this.bufferedBytes -= eventBytes;
1301
1303
  this.sendingEvents = batch.length;
1302
- if (report !== null && fits(report)) {
1303
- report.alone = batch.length === 0;
1304
- batch.push(report);
1305
- }
1304
+ if (report !== null) batch.push(report);
1306
1305
  return batch.length > 0 ? batch : null;
1307
1306
  }
1308
- /** Puts a kept batch's events back at the head of the buffer; `true` when
1309
- * there were none. */
1310
- putBack(kept) {
1307
+ /** Puts what a failure `kept` of the batch `taken` back at the head of the
1308
+ * buffer, and keeps its report unless `taken` had no events; `true` when
1309
+ * nothing was kept. */
1310
+ putBack(kept, taken) {
1311
1311
  this.sendingEvents = 0;
1312
1312
  if (this.closed) return kept.length === 0;
1313
1313
  const events = [];
1314
1314
  for (const waiting of kept) {
1315
1315
  if (waiting.reportSum !== void 0) {
1316
- if (waiting.alone || this.batchless) this.pendingReport = null;
1316
+ if (taken.every((w) => w.reportSum !== void 0) || this.batchless) this.pendingReport = null;
1317
1317
  continue;
1318
1318
  }
1319
1319
  events.push(waiting);
@@ -1342,17 +1342,21 @@ var HttpSink = class _HttpSink {
1342
1342
  }
1343
1343
  buildReport() {
1344
1344
  if (this.pendingReport === null) return null;
1345
+ const { tenant_id, vendor_id, consent_token } = this.pendingReport;
1345
1346
  const totals = PROCESS_DROPS.total();
1346
1347
  try {
1347
1348
  const report = ClientReportEventSchema.parse({
1348
- ...this.pendingReport,
1349
+ tenant_id,
1350
+ vendor_id,
1351
+ consent_token,
1349
1352
  session_id: PROCESS_DROPS.instanceId,
1350
1353
  sequence_number: nextClockSequence(),
1351
1354
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1352
1355
  payload: { instance_id: PROCESS_DROPS.instanceId, dropped: totals }
1353
1356
  });
1354
1357
  const json = JSON.stringify(report);
1355
- return { event: report, json, bytes: utf8Bytes(json), writtenAt: Date.now(), reportSum: sum(Object.values(totals)) };
1358
+ this.pendingReport.built = { event: report, json, bytes: utf8Bytes(json), writtenAt: Date.now(), reportSum: sum(Object.values(totals)) };
1359
+ return this.pendingReport.built;
1356
1360
  } catch {
1357
1361
  this.pendingReport = null;
1358
1362
  return null;
@@ -2461,6 +2465,18 @@ function resolveTenantId(explicit, vendorId2) {
2461
2465
  if (fromEnv2) return fromEnv2;
2462
2466
  return vendorId2;
2463
2467
  }
2468
+ var STAND_IN_VENDOR_ID = "unset";
2469
+ function resolveInstallConfig(config) {
2470
+ const unconfigured = !config.dsn && dsnFromEnvironment() === void 0 && !config.vendorId && !config.tenantId && config.sink === void 0;
2471
+ const resolved = resolveBatonConfig(
2472
+ unconfigured ? {
2473
+ ...config,
2474
+ vendorId: STAND_IN_VENDOR_ID,
2475
+ vendorDisplayName: config.vendorDisplayName ?? STAND_IN_VENDOR_ID
2476
+ } : config
2477
+ );
2478
+ return { resolved, unconfigured };
2479
+ }
2464
2480
  function resolveBatonConfig(config) {
2465
2481
  const dsnString = selectDsn(
2466
2482
  config.dsn,
@@ -2592,11 +2608,12 @@ function captureDisabled() {
2592
2608
  return null;
2593
2609
  }
2594
2610
  function logDisabled(switchName, surface) {
2595
- if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
2596
- process.emitWarning(
2597
- `baton: ${switchName} is set, so capture is OFF \u2014 ${surface} installed nothing and will emit no events. Unset it to re-enable.`
2598
- );
2599
- }
2611
+ warn(
2612
+ `baton: ${switchName} is set, so capture is OFF \u2014 ${surface} installed nothing and will emit no events. Unset it to re-enable.`
2613
+ );
2614
+ }
2615
+ function logUnconfigured(surface) {
2616
+ warn(`baton: no DSN (dsn or BATON_DSN), so ${surface} installed nothing and records nothing`);
2600
2617
  }
2601
2618
  var DisabledSink = class {
2602
2619
  // The parameter is omitted rather than named-and-ignored: a narrower
@@ -2675,6 +2692,19 @@ var SessionCounter = class {
2675
2692
  return next;
2676
2693
  }
2677
2694
  };
2695
+ var ServerCounter = class extends SessionCounter {
2696
+ constructor(shared, ownSessionId) {
2697
+ super();
2698
+ this.shared = shared;
2699
+ this.ownSessionId = ownSessionId;
2700
+ }
2701
+ shared;
2702
+ ownSessionId;
2703
+ ownSequence = 0;
2704
+ next(sessionId) {
2705
+ return sessionId === this.ownSessionId ? ++this.ownSequence : this.shared.next(sessionId);
2706
+ }
2707
+ };
2678
2708
 
2679
2709
  // src/integrations/mcp/zodCompat.ts
2680
2710
  var z3rt = __toESM(require("zod/v3"), 1);
@@ -2892,6 +2922,7 @@ function buildSeamAugmentations(options) {
2892
2922
  var BATON_WRAPPED = /* @__PURE__ */ Symbol("batonWrapped");
2893
2923
  var wired = /* @__PURE__ */ new WeakSet();
2894
2924
  var CLEAN_OUTCOME = { failed: false, raised: false, result: void 0 };
2925
+ var INTENT_PARAM_NAMES = [USER_GOAL_PARAM_NAME, ...RETIRED_PARAM_NAMES];
2895
2926
  var callSlots = new import_node_async_hooks.AsyncLocalStorage();
2896
2927
  var SurfaceState = class {
2897
2928
  constructor(serverMeta, sentSurfaces) {
@@ -2954,14 +2985,14 @@ async function resolveEnvelopeParts(ctx, extra) {
2954
2985
  const session = await resolveSessionId(ctx.fallbackSessionId, extra);
2955
2986
  return { ...session, scrubbedMeta };
2956
2987
  }
2957
- async function openCall(ctx, toolName, extra, params, retired, registered = true) {
2988
+ async function openCall(ctx, toolName, extra, params, stripped, registered = true) {
2958
2989
  await maybeEmitSurfaceSnapshot(ctx);
2959
2990
  const { scrubbedMeta, ...session } = await resolveEnvelopeParts(ctx, extra);
2960
2991
  const dispositions = ctx.paramRegistry.get(toolName);
2961
- const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, registered);
2992
+ const rawIntent = stripped[USER_GOAL_PARAM_NAME] ?? extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, registered);
2962
2993
  const scrubbedIntent = scrubOrNull(ctx.scrubber, rawIntent, USER_GOAL_PARAM_NAME);
2963
2994
  const [scrubbedExpected = null, scrubbedWorkflow = null] = RETIRED_PARAM_NAMES.map(
2964
- (name) => dispositions === void 0 || dispositions[name] === "native" ? null : scrubOrNull(ctx.scrubber, retired[name] ?? popText(params, name), name)
2995
+ (name) => dispositions === void 0 || dispositions[name] === "native" ? null : scrubOrNull(ctx.scrubber, stripped[name] ?? popText(params, name), name)
2965
2996
  );
2966
2997
  const caller = await resolveCaller(
2967
2998
  ctx.resolvePrincipal,
@@ -3011,9 +3042,9 @@ function batonWrap(nameRef, original, ctx) {
3011
3042
  if (slot) slot.innerFired = true;
3012
3043
  const extra = callArgs[callArgs.length - 1];
3013
3044
  const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
3014
- const retired = slot?.retired ?? {};
3015
- if (slot) slot.retired = {};
3016
- const { common, session } = await openCall(ctx, toolName, extra, params, retired);
3045
+ const stripped = slot?.strippedFor === toolName ? slot.stripped : {};
3046
+ if (slot) slot.strippedFor = null;
3047
+ const { common, session } = await openCall(ctx, toolName, extra, params, stripped);
3017
3048
  const terminate = async (build, replacement) => {
3018
3049
  if (!slot) {
3019
3050
  if (build !== null) await emit(ctx.sink, build);
@@ -3189,19 +3220,19 @@ function popText(args, paramName) {
3189
3220
  delete args[paramName];
3190
3221
  return typeof raw === "string" && !isBlank(raw) ? raw : null;
3191
3222
  }
3192
- function stripRetiredParams(params, ctx) {
3223
+ function stripIntentParams(params, ctx) {
3193
3224
  const toolName = params?.name;
3194
3225
  const args = params?.arguments;
3195
3226
  if (typeof toolName !== "string") return {};
3196
3227
  if (toolName === ctx.annotationToolName) return {};
3197
3228
  if (typeof args !== "object" || args === null || Array.isArray(args)) return {};
3198
3229
  const dispositions = ctx.paramRegistry.get(toolName);
3199
- const retired = {};
3200
- for (const name of RETIRED_PARAM_NAMES) {
3230
+ const stripped = {};
3231
+ for (const name of INTENT_PARAM_NAMES) {
3201
3232
  if (dispositions === void 0 || dispositions[name] === "native" || !(name in args)) continue;
3202
- retired[name] = popText(args, name);
3233
+ stripped[name] = popText(args, name);
3203
3234
  }
3204
- return retired;
3235
+ return stripped;
3205
3236
  }
3206
3237
  async function maybeEmitSurfaceSnapshot(ctx) {
3207
3238
  if (!ctx.surfaceState.dirty) return;
@@ -3237,7 +3268,7 @@ async function maybeEmitSurfaceSnapshot(ctx) {
3237
3268
  }
3238
3269
  function declaredIntentParams(vendorSchema) {
3239
3270
  const declared2 = {};
3240
- for (const name of [USER_GOAL_PARAM_NAME, ...RETIRED_PARAM_NAMES]) {
3271
+ for (const name of INTENT_PARAM_NAMES) {
3241
3272
  if (declaresParam(vendorSchema, name)) declared2[name] = "native";
3242
3273
  }
3243
3274
  return declared2;
@@ -3503,10 +3534,12 @@ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
3503
3534
  TOOLS_CALL_SEAM,
3504
3535
  (handler) => async (...args) => {
3505
3536
  const request = args[0];
3537
+ const name = request?.params?.name;
3506
3538
  const slot = {
3507
3539
  innerFired: false,
3508
3540
  flushTerminal: null,
3509
- retired: stripRetiredParams(request?.params, ctx),
3541
+ stripped: stripIntentParams(request?.params, ctx),
3542
+ strippedFor: typeof name === "string" ? name : null,
3510
3543
  validation: "unseen"
3511
3544
  };
3512
3545
  let outcome = CLEAN_OUTCOME;
@@ -3572,7 +3605,7 @@ async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
3572
3605
  toolName,
3573
3606
  args[1],
3574
3607
  params,
3575
- slot.retired,
3608
+ slot.stripped,
3576
3609
  entry != null
3577
3610
  );
3578
3611
  const failureKind = requestSideFailureKind(entry, slot.validation);
@@ -3681,23 +3714,13 @@ function withBaton(server, supplied = {}) {
3681
3714
  const disabledBy = captureDisabled();
3682
3715
  if (disabledBy !== null) {
3683
3716
  logDisabled(disabledBy, "withBaton");
3684
- return new BatonHandle({
3685
- // A sink the VENDOR constructed is held rather than dropped, so their
3686
- // `handle.aclose()` still releases it — we took ownership of that object
3687
- // the moment they passed it, and the switch does not undo that. Nothing
3688
- // writes to it: nothing is wrapped.
3689
- sink: supplied.sink ?? new DisabledSink(),
3690
- // Empty, and a constant, because when the switch is on nothing was
3691
- // resolved: inventing a session id would put a real identifier on a
3692
- // handle whose whole meaning is that no events exist under it.
3693
- vendorId: "",
3694
- sessionId: "baton-disabled",
3695
- annotationToolName: ""
3696
- });
3717
+ return inertHandle(supplied.sink ?? new DisabledSink(), "baton-disabled");
3697
3718
  }
3698
- const resolved = resolveBatonConfig(supplied);
3699
- warnUnusedReportSettings(resolved);
3700
- return install(server, supplied, resolved, new SentSurfaces(), /* @__PURE__ */ new Set());
3719
+ const { resolved, unconfigured } = resolveInstallConfig(supplied);
3720
+ if (!unconfigured) warnUnusedReportSettings(resolved);
3721
+ const handle = install(server, supplied, resolved, newBatonState(resolved), unconfigured);
3722
+ if (unconfigured) logUnconfigured("withBaton");
3723
+ return handle;
3701
3724
  }
3702
3725
  function createBaton(supplied = {}) {
3703
3726
  const disabledBy = captureDisabled();
@@ -3711,40 +3734,61 @@ function createBaton(supplied = {}) {
3711
3734
  aclose: () => boundedSinkCall(unused, "aclose")
3712
3735
  };
3713
3736
  }
3714
- const resolved = resolveBatonConfig(supplied);
3715
- warnUnusedReportSettings(resolved);
3737
+ const { resolved, unconfigured } = resolveInstallConfig(supplied);
3716
3738
  if (resolved.reportMode === "on") deriveAnnotationToolName(resolved.vendorId, supplied.annotationToolName);
3717
- const sink = resolved.sink ?? new StdoutSink();
3739
+ if (unconfigured) logUnconfigured("createBaton");
3740
+ else warnUnusedReportSettings(resolved);
3741
+ const sink = unconfigured ? new DisabledSink() : resolved.sink ?? new StdoutSink();
3718
3742
  const config = {
3719
3743
  ...resolved,
3720
3744
  sink,
3721
3745
  tenantId: resolveTenantId(resolved.tenantId, resolved.vendorId)
3722
3746
  };
3723
- const sentSurfaces = new SentSurfaces();
3724
- const warned3 = /* @__PURE__ */ new Set();
3747
+ const state = newBatonState(resolved);
3725
3748
  return {
3726
3749
  wrap: (server) => {
3727
- install(server, supplied, config, sentSurfaces, warned3);
3750
+ install(server, supplied, config, state, unconfigured);
3728
3751
  },
3729
3752
  flush: () => boundedSinkCall(sink, "flush"),
3730
3753
  aclose: () => boundedSinkCall(sink, "aclose")
3731
3754
  };
3732
3755
  }
3733
- function install(server, supplied, resolved, sentSurfaces, warned3) {
3756
+ function inertHandle(sink, sessionId) {
3757
+ return new BatonHandle({ sink, sessionId, vendorId: "", annotationToolName: "" });
3758
+ }
3759
+ function requireHighLevelServer(server) {
3760
+ const candidate = server;
3761
+ if (typeof candidate?.registerTool !== "function" || typeof candidate.server !== "object" || candidate.server === null) {
3762
+ throw new TypeError(
3763
+ "Baton needs a high-level McpServer (from @modelcontextprotocol/sdk/server/mcp.js or @modelcontextprotocol/server); the low-level Server is not supported."
3764
+ );
3765
+ }
3766
+ }
3767
+ function newBatonState(config) {
3768
+ return {
3769
+ sentSurfaces: new SentSurfaces(),
3770
+ warned: /* @__PURE__ */ new Set(),
3771
+ counter: new SessionCounter(),
3772
+ scrubber: config.scrubber ?? new Scrubber().scrub
3773
+ };
3774
+ }
3775
+ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, counter: sharedCounter, scrubber }, unconfigured) {
3776
+ requireHighLevelServer(server);
3734
3777
  const internals = server;
3735
3778
  const serverName = usableServerName(() => ({
3736
3779
  name: internals.server._serverInfo?.name,
3737
3780
  className: internals.constructor.name
3738
3781
  }));
3739
3782
  const config = resolved.reportMode === "on" ? withServerDisplayName(resolved, supplied, serverName) : resolved;
3740
- const sink = config.sink ?? new StdoutSink();
3741
3783
  const reports = reportsFor(config);
3742
3784
  const annotationToolName = reports ? resolveAnnotationToolName(serverName, { ...config, vendorDisplayName: reports.vendorDisplayName }) : "";
3785
+ const ours = reports ? buildServerInstructions({ vendorDisplayName: reports.vendorDisplayName, annotationToolName }) : INTENT_INSTRUCTIONS;
3786
+ if (unconfigured) return inertHandle(new DisabledSink(), "baton-unconfigured");
3787
+ const sink = config.sink ?? new StdoutSink();
3743
3788
  const intentParamMode = config.intentParamMode ?? DEFAULT_INTENT_PARAM_MODE;
3744
- const counter2 = new SessionCounter();
3745
3789
  const fallbackSessionId = `sdk-${uuid7()}`;
3790
+ const counter2 = new ServerCounter(sharedCounter, fallbackSessionId);
3746
3791
  const tenantId = resolveTenantId(config.tenantId, config.vendorId);
3747
- const scrubber = config.scrubber ?? new Scrubber().scrub;
3748
3792
  const serverMeta = buildServerMeta(server.server);
3749
3793
  const surfaceState = new SurfaceState(serverMeta, sentSurfaces);
3750
3794
  const emitSurface = async (sessionId, digest, snapshot) => {
@@ -3839,7 +3883,6 @@ function install(server, supplied, resolved, sentSurfaces, warned3) {
3839
3883
  surfaceState,
3840
3884
  emitSurface
3841
3885
  };
3842
- const ours = reports ? buildServerInstructions({ vendorDisplayName: reports.vendorDisplayName, annotationToolName }) : INTENT_INSTRUCTIONS;
3843
3886
  internals.server._instructions = withVendorInstructions(
3844
3887
  internals.server,
3845
3888
  ours,