@brizz/sdk 0.1.40 → 0.1.42

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.
Files changed (29) hide show
  1. package/README.md +25 -0
  2. package/dist/{chunk-EC3MYSRM.js → chunk-7FQQHF5U.js} +1 -1
  3. package/dist/{chunk-77UGZGMP.cjs → chunk-FORVS4QW.cjs} +5 -1
  4. package/dist/{chunk-RNU3DOSR.cjs → chunk-K3NPYISB.cjs} +1 -1
  5. package/dist/{chunk-BGLKBQ6N.js → chunk-KVOGOKOB.js} +1 -1
  6. package/dist/{chunk-EVRCHF74.cjs → chunk-QUV5HYJ2.cjs} +4 -4
  7. package/dist/{chunk-WII4R5RE.js → chunk-Y7NMZAQT.js} +4 -0
  8. package/dist/index.cjs +350 -229
  9. package/dist/index.js +205 -84
  10. package/dist/interrupt-3NXOTY4N.cjs +12 -0
  11. package/dist/{interrupt-YJVZK4VC.js → interrupt-ERCX5RXR.js} +2 -2
  12. package/dist/{mcp-HBOMHU67.js → mcp-5BFXKN63.js} +50 -34
  13. package/dist/{mcp-64ZNSCIR.cjs → mcp-GVGTOWHP.cjs} +61 -45
  14. package/dist/types/cjs/index.d.ts +1 -1
  15. package/dist/types/cjs/internal/instrumentation/mcp/session.d.ts +1 -0
  16. package/dist/types/cjs/internal/log/logging.d.ts +5 -5
  17. package/dist/types/cjs/internal/semantic-conventions.d.ts +2 -0
  18. package/dist/types/cjs/internal/trace/exporters/span-exporter.d.ts +11 -2
  19. package/dist/types/cjs/internal/trace/index.d.ts +1 -1
  20. package/dist/types/cjs/internal/trace/session.d.ts +4 -0
  21. package/dist/types/esm/index.d.ts +1 -1
  22. package/dist/types/esm/internal/instrumentation/mcp/session.d.ts +1 -0
  23. package/dist/types/esm/internal/log/logging.d.ts +5 -5
  24. package/dist/types/esm/internal/semantic-conventions.d.ts +2 -0
  25. package/dist/types/esm/internal/trace/exporters/span-exporter.d.ts +11 -2
  26. package/dist/types/esm/internal/trace/index.d.ts +1 -1
  27. package/dist/types/esm/internal/trace/session.d.ts +4 -0
  28. package/package.json +13 -13
  29. package/dist/interrupt-DM3AWSBX.cjs +0 -12
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  } from "./chunk-7SUF4VVI.js";
5
5
  import {
6
6
  getSDKVersion
7
- } from "./chunk-BGLKBQ6N.js";
7
+ } from "./chunk-KVOGOKOB.js";
8
8
  import {
9
9
  DEFAULT_LOG_LEVEL,
10
10
  LogLevel,
@@ -15,7 +15,7 @@ import {
15
15
  } from "./chunk-Y4HNUX3Q.js";
16
16
  import {
17
17
  InterruptPropagator
18
- } from "./chunk-EC3MYSRM.js";
18
+ } from "./chunk-7FQQHF5U.js";
19
19
  import {
20
20
  BRIZZ,
21
21
  EXTERNAL_LINK_EVENT_NAME,
@@ -52,6 +52,8 @@ import {
52
52
  ORGANIZATION_PLAN,
53
53
  PROPERTIES_CONTEXT_KEY,
54
54
  RESERVED_METRIC_NAMES,
55
+ SERVICE_NAME,
56
+ SERVICE_NAME_ATTRIBUTE,
55
57
  SESSION_ID,
56
58
  SESSION_INPUT,
57
59
  SESSION_INPUT_CONTEXT,
@@ -67,7 +69,7 @@ import {
67
69
  USER_NAME,
68
70
  USER_PLAN,
69
71
  USER_ROLE
70
- } from "./chunk-WII4R5RE.js";
72
+ } from "./chunk-Y7NMZAQT.js";
71
73
  import {
72
74
  __require
73
75
  } from "./chunk-3RG5ZIWI.js";
@@ -124,7 +126,7 @@ function loadGenAIInstrumentations() {
124
126
  function loadMCPInstrumentation() {
125
127
  void (async () => {
126
128
  try {
127
- const { MCPInstrumentation } = await import("./mcp-HBOMHU67.js");
129
+ const { MCPInstrumentation } = await import("./mcp-5BFXKN63.js");
128
130
  const mcp = new MCPInstrumentation({ exceptionLogger });
129
131
  registerInstrumentations({ instrumentations: [mcp] });
130
132
  logger.debug("Auto-loaded MCP instrumentation");
@@ -180,7 +182,7 @@ function loadVercelAITelemetry() {
180
182
  }
181
183
  const isV7 = typeof ai.registerTelemetry === "function";
182
184
  const integrations = [];
183
- const { createInterruptIntegration } = await import("./interrupt-YJVZK4VC.js");
185
+ const { createInterruptIntegration } = await import("./interrupt-ERCX5RXR.js");
184
186
  integrations.push(createInterruptIntegration());
185
187
  let otelCollectorLoaded = false;
186
188
  try {
@@ -507,7 +509,7 @@ var InstrumentationRegistry = class _InstrumentationRegistry {
507
509
  const mcpModules = this.manualModules.mcp;
508
510
  void (async () => {
509
511
  try {
510
- const { MCPInstrumentation } = await import("./mcp-HBOMHU67.js");
512
+ const { MCPInstrumentation } = await import("./mcp-5BFXKN63.js");
511
513
  const instrumentation = new MCPInstrumentation({ exceptionLogger: exceptionLogger2 });
512
514
  instrumentation.manuallyInstrument(mcpModules);
513
515
  logger.debug("Manual instrumentation enabled for MCP");
@@ -547,9 +549,7 @@ var InstrumentationRegistry = class _InstrumentationRegistry {
547
549
  import { SeverityNumber } from "@opentelemetry/api-logs";
548
550
  import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-http";
549
551
  import { resourceFromAttributes } from "@opentelemetry/resources";
550
- import {
551
- LoggerProvider
552
- } from "@opentelemetry/sdk-logs";
552
+ import { LoggerProvider } from "@opentelemetry/sdk-logs";
553
553
 
554
554
  // src/internal/trace/session.ts
555
555
  import { context, trace, SpanStatusCode } from "@opentelemetry/api";
@@ -654,6 +654,42 @@ function setSessionId(id) {
654
654
  setCurrentSpanCustomProperties(properties);
655
655
  propagatePropertiesImperatively(properties);
656
656
  }
657
+ var SERVICE_NAME_MAX_BYTES = 256;
658
+ function serviceNameProperties(name) {
659
+ if (typeof name !== "string" || name === "") {
660
+ logger.warn("Service name must be a non-empty string; keeping the configured appName.");
661
+ return {};
662
+ }
663
+ if (/[\r\n\0]/.test(name)) {
664
+ logger.warn(
665
+ `Service name ${JSON.stringify(name)} contains CR, LF, or NUL; keeping the configured appName.`
666
+ );
667
+ return {};
668
+ }
669
+ const byteLength = new globalThis.TextEncoder().encode(name).length;
670
+ if (byteLength > SERVICE_NAME_MAX_BYTES) {
671
+ logger.warn(
672
+ `Service name is ${byteLength} bytes, over the ${SERVICE_NAME_MAX_BYTES}-byte limit; keeping the configured appName.`
673
+ );
674
+ return {};
675
+ }
676
+ return { [SERVICE_NAME]: name };
677
+ }
678
+ function setServiceName(name) {
679
+ const properties = serviceNameProperties(name);
680
+ setCurrentSpanCustomProperties(properties);
681
+ propagatePropertiesImperatively(properties);
682
+ }
683
+ function callWithServiceName(name, fn, thisArg, ...args) {
684
+ return callWithProperties(serviceNameProperties(name), fn, thisArg, ...args);
685
+ }
686
+ function withServiceName(name, fn, thisArg) {
687
+ return withProperties(serviceNameProperties(name), fn, thisArg);
688
+ }
689
+ function resolveServiceNameFromContext() {
690
+ const props = context.active().getValue(PROPERTIES_CONTEXT_KEY);
691
+ return props?.[SERVICE_NAME];
692
+ }
657
693
  function userProperties(user) {
658
694
  const properties = { [USER_ID]: user.id };
659
695
  if (user.email !== void 0) {
@@ -1708,67 +1744,41 @@ var LoggingModule = class _LoggingModule {
1708
1744
  }
1709
1745
  return this.instance;
1710
1746
  }
1711
- logExporter = null;
1712
- logProcessor = null;
1747
+ config = null;
1713
1748
  loggerProvider = null;
1749
+ /** Providers for scoped service names, keyed by service name. */
1750
+ scopedProviders = /* @__PURE__ */ new Map();
1714
1751
  /**
1715
- * Initialize the log exporter
1752
+ * Build the log exporter for a service. The service header is fixed per
1753
+ * exporter and the gateway rewrites service.name from it, so each service
1754
+ * needs its own. A custom exporter is used as-is — the resource still
1755
+ * carries the right service.name.
1716
1756
  */
1717
- initLogExporter(config) {
1718
- if (this.logExporter) {
1719
- logger.debug("Log exporter already initialized, skipping re-initialization");
1720
- return;
1721
- }
1757
+ createLogExporter(config, serviceName) {
1722
1758
  if (config.customLogExporter) {
1723
1759
  logger.debug("Using custom log exporter");
1724
- this.logExporter = config.customLogExporter;
1725
- logger.debug("Custom log exporter initialized successfully");
1726
- return;
1760
+ return config.customLogExporter;
1727
1761
  }
1728
1762
  const logsUrl = config.baseUrl.replace(/\/$/, "") + "/v1/logs";
1729
- logger.debug("Initializing default OTLP log exporter", { url: logsUrl });
1730
- const headers = { ...config.headers };
1731
- this.logExporter = new OTLPLogExporter({
1732
- url: logsUrl,
1733
- headers
1734
- });
1735
- logger.debug("OTLP log exporter initialized successfully");
1763
+ logger.debug("Initializing default OTLP log exporter", { url: logsUrl, serviceName });
1764
+ const headers = serviceName === config.appName ? { ...config.headers } : { ...config.headers, [SERVICE_NAME_HEADER]: serviceName };
1765
+ return new OTLPLogExporter({ url: logsUrl, headers });
1736
1766
  }
1737
1767
  /**
1738
- * Initialize the log processor with masking support
1768
+ * Build a logger provider reporting under `serviceName`, with its own
1769
+ * exporter and masking-aware processor.
1739
1770
  */
1740
- initLogProcessor(config) {
1741
- if (this.logProcessor) {
1742
- logger.debug("Log processor already initialized, skipping re-initialization");
1743
- return;
1744
- }
1745
- if (!this.logExporter) {
1746
- throw new Error("Log exporter must be initialized before processor");
1747
- }
1748
- logger.debug("Initializing log processor", {
1771
+ createLoggerProvider(config, serviceName) {
1772
+ logger.debug("Creating logger provider", {
1773
+ serviceName,
1749
1774
  disableBatch: config.disableBatch,
1750
1775
  hasMasking: !!config.masking?.eventMasking
1751
1776
  });
1752
- this.logProcessor = config.disableBatch ? new BrizzSimpleLogRecordProcessor(this.logExporter, config) : new BrizzBatchLogRecordProcessor(this.logExporter, config);
1753
- logger.debug("Log processor initialized successfully");
1754
- }
1755
- /**
1756
- * Initialize the logger provider
1757
- */
1758
- initLoggerProvider(config) {
1759
- if (this.loggerProvider) {
1760
- logger.debug("Logger provider already initialized, skipping re-initialization");
1761
- return;
1762
- }
1763
- if (!this.logProcessor) {
1764
- throw new Error("Log processor must be initialized before logger provider");
1765
- }
1766
- logger.debug("Creating resource with service name", {
1767
- serviceName: config.appName
1768
- });
1777
+ const exporter = this.createLogExporter(config, serviceName);
1778
+ const processor = config.disableBatch ? new BrizzSimpleLogRecordProcessor(exporter, config) : new BrizzBatchLogRecordProcessor(exporter, config);
1769
1779
  const resourceAttributes = {
1770
1780
  ...config.resourceAttributes,
1771
- "service.name": config.appName,
1781
+ "service.name": serviceName,
1772
1782
  [BRIZZ_SDK_VERSION]: getSDKVersion(),
1773
1783
  [BRIZZ_SDK_LANGUAGE]: SDK_LANGUAGE
1774
1784
  };
@@ -1778,22 +1788,38 @@ var LoggingModule = class _LoggingModule {
1778
1788
  if (config.appVersion) {
1779
1789
  resourceAttributes["service.version"] = config.appVersion;
1780
1790
  }
1781
- const resource = resourceFromAttributes(resourceAttributes);
1782
- logger.debug("Creating logger provider with resource");
1783
- this.loggerProvider = new LoggerProvider({
1784
- resource,
1785
- processors: [this.logProcessor]
1791
+ return new LoggerProvider({
1792
+ resource: resourceFromAttributes(resourceAttributes),
1793
+ processors: [processor]
1786
1794
  });
1787
- logger.debug("Logger provider initialization completed");
1795
+ }
1796
+ /**
1797
+ * The provider events emit through: the scoped service name from
1798
+ * `callWithServiceName`, else the configured appName.
1799
+ */
1800
+ activeLoggerProvider() {
1801
+ const serviceName = resolveServiceNameFromContext();
1802
+ if (!serviceName || !this.config || serviceName === this.config.appName) {
1803
+ return this.loggerProvider;
1804
+ }
1805
+ let provider = this.scopedProviders.get(serviceName);
1806
+ if (!provider) {
1807
+ provider = this.createLoggerProvider(this.config, serviceName);
1808
+ this.scopedProviders.set(serviceName, provider);
1809
+ }
1810
+ return provider;
1788
1811
  }
1789
1812
  /**
1790
1813
  * Initialize the logging module with the provided configuration
1791
1814
  */
1792
1815
  setup(config) {
1793
1816
  logger.info("Setting up logging module");
1794
- this.initLogExporter(config);
1795
- this.initLogProcessor(config);
1796
- this.initLoggerProvider(config);
1817
+ this.config = config;
1818
+ if (this.loggerProvider) {
1819
+ logger.debug("Logger provider already initialized, skipping re-initialization");
1820
+ } else {
1821
+ this.loggerProvider = this.createLoggerProvider(config, config.appName);
1822
+ }
1797
1823
  _LoggingModule.instance = this;
1798
1824
  logger.info("Logging module setup completed");
1799
1825
  }
@@ -1808,7 +1834,8 @@ var LoggingModule = class _LoggingModule {
1808
1834
  hasBody: !!body,
1809
1835
  severityNumber
1810
1836
  });
1811
- if (!this.loggerProvider) {
1837
+ const provider = this.activeLoggerProvider();
1838
+ if (!provider) {
1812
1839
  logger.error("Cannot emit event: Logger provider not initialized");
1813
1840
  throw new Error("Logging module not initialized");
1814
1841
  }
@@ -1818,7 +1845,7 @@ var LoggingModule = class _LoggingModule {
1818
1845
  logger.debug("Combined log attributes", { attributes: Object.keys(logAttributes) });
1819
1846
  }
1820
1847
  logger.debug("Getting logger instance for brizz_events");
1821
- const eventLogger = this.loggerProvider.getLogger("brizz.events");
1848
+ const eventLogger = provider.getLogger("brizz.events");
1822
1849
  logger.debug("Emitting log record with eventName", { eventName: name });
1823
1850
  try {
1824
1851
  eventLogger.emit({
@@ -1860,8 +1887,9 @@ var LoggingModule = class _LoggingModule {
1860
1887
  await this.loggerProvider.shutdown();
1861
1888
  this.loggerProvider = null;
1862
1889
  }
1863
- this.logProcessor = null;
1864
- this.logExporter = null;
1890
+ await Promise.all([...this.scopedProviders.values()].map(async (p) => p.shutdown()));
1891
+ this.scopedProviders.clear();
1892
+ this.config = null;
1865
1893
  if (_LoggingModule.instance === this) {
1866
1894
  _LoggingModule.instance = null;
1867
1895
  }
@@ -1987,10 +2015,16 @@ import { ExportResultCode } from "@opentelemetry/core";
1987
2015
  import { resourceFromAttributes as resourceFromAttributes2 } from "@opentelemetry/resources";
1988
2016
  var BrizzSpanExporter = class {
1989
2017
  _delegate;
1990
- _brizzResource;
2018
+ _delegateFactory;
2019
+ _defaultServiceName;
2020
+ _resourceAttrs;
2021
+ _resources = /* @__PURE__ */ new Map();
2022
+ _delegates = /* @__PURE__ */ new Map();
1991
2023
  _beforeSendSpan;
1992
- constructor(delegate, config) {
2024
+ constructor(delegate, config, factory) {
1993
2025
  this._delegate = delegate;
2026
+ this._delegateFactory = factory;
2027
+ this._defaultServiceName = config.appName;
1994
2028
  const resourceAttrs = {
1995
2029
  ...config.resourceAttributes,
1996
2030
  "service.name": config.appName,
@@ -2003,24 +2037,63 @@ var BrizzSpanExporter = class {
2003
2037
  if (config.appVersion) {
2004
2038
  resourceAttrs["service.version"] = config.appVersion;
2005
2039
  }
2006
- this._brizzResource = resourceFromAttributes2(resourceAttrs);
2040
+ this._resourceAttrs = resourceAttrs;
2007
2041
  this._beforeSendSpan = config.beforeSendSpan;
2008
2042
  }
2043
+ /** The service a span reports under: its scoped override, else the configured appName. */
2044
+ _serviceNameOf(span) {
2045
+ const value = span.attributes[SERVICE_NAME_ATTRIBUTE];
2046
+ return typeof value === "string" && value !== "" ? value : this._defaultServiceName;
2047
+ }
2048
+ _resourceFor(serviceName) {
2049
+ let resource = this._resources.get(serviceName);
2050
+ if (!resource) {
2051
+ resource = resourceFromAttributes2({ ...this._resourceAttrs, "service.name": serviceName });
2052
+ this._resources.set(serviceName, resource);
2053
+ }
2054
+ return resource;
2055
+ }
2056
+ /**
2057
+ * Without a factory (a custom exporter, e.g. in tests) every service shares the
2058
+ * one delegate — the patched Resource still carries the right service.name.
2059
+ */
2060
+ _delegateFor(serviceName) {
2061
+ if (serviceName === this._defaultServiceName || !this._delegateFactory) {
2062
+ return this._delegate;
2063
+ }
2064
+ let delegate = this._delegates.get(serviceName);
2065
+ if (!delegate) {
2066
+ delegate = this._delegateFactory(serviceName);
2067
+ this._delegates.set(serviceName, delegate);
2068
+ }
2069
+ return delegate;
2070
+ }
2009
2071
  export(spans, resultCallback) {
2010
2072
  if (spans.length === 0) {
2011
2073
  resultCallback({ code: ExportResultCode.SUCCESS });
2012
2074
  return;
2013
2075
  }
2014
- const patchedSpans = spans.map((span) => ({
2015
- ...span,
2016
- resource: span.resource.merge(this._brizzResource),
2017
- spanContext: span.spanContext.bind(span)
2018
- }));
2076
+ const groups = /* @__PURE__ */ new Map();
2077
+ for (const span of spans) {
2078
+ const serviceName = this._serviceNameOf(span);
2079
+ const patched = {
2080
+ ...span,
2081
+ resource: span.resource.merge(this._resourceFor(serviceName)),
2082
+ spanContext: span.spanContext.bind(span)
2083
+ };
2084
+ const group = groups.get(serviceName);
2085
+ if (group) {
2086
+ group.push(patched);
2087
+ } else {
2088
+ groups.set(serviceName, [patched]);
2089
+ }
2090
+ }
2019
2091
  const filter = this._beforeSendSpan;
2020
2092
  if (!filter) {
2021
- this._delegate.export(patchedSpans, resultCallback);
2093
+ this._exportGroups(groups, resultCallback);
2022
2094
  return;
2023
2095
  }
2096
+ const patchedSpans = [...groups.values()].flat();
2024
2097
  const verdicts = patchedSpans.map((span) => {
2025
2098
  try {
2026
2099
  return Promise.resolve(filter(span));
@@ -2030,23 +2103,61 @@ var BrizzSpanExporter = class {
2030
2103
  }
2031
2104
  });
2032
2105
  Promise.all(verdicts).then((keep) => {
2033
- const filtered = patchedSpans.filter((_, i) => keep[i] !== false);
2034
- if (filtered.length === 0) {
2106
+ const kept = new Set(patchedSpans.filter((_, i) => keep[i] !== false));
2107
+ const filtered = /* @__PURE__ */ new Map();
2108
+ for (const [serviceName, group] of groups) {
2109
+ const remaining = group.filter((span) => kept.has(span));
2110
+ if (remaining.length > 0) {
2111
+ filtered.set(serviceName, remaining);
2112
+ }
2113
+ }
2114
+ if (filtered.size === 0) {
2035
2115
  resultCallback({ code: ExportResultCode.SUCCESS });
2036
2116
  return;
2037
2117
  }
2038
- this._delegate.export(filtered, resultCallback);
2118
+ this._exportGroups(filtered, resultCallback);
2039
2119
  return;
2040
2120
  }).catch((error) => {
2041
2121
  logger.warn("beforeSendSpan rejected; all spans will be kept", { error });
2042
- this._delegate.export(patchedSpans, resultCallback);
2122
+ this._exportGroups(groups, resultCallback);
2043
2123
  });
2044
2124
  }
2125
+ /**
2126
+ * Dispatch each service's spans to its own exporter, reporting the first
2127
+ * failure once every group has answered.
2128
+ */
2129
+ _exportGroups(groups, resultCallback) {
2130
+ const entries = [...groups.entries()];
2131
+ const only = entries[0];
2132
+ if (entries.length === 1 && only) {
2133
+ this._delegateFor(only[0]).export(only[1], resultCallback);
2134
+ return;
2135
+ }
2136
+ let pending = entries.length;
2137
+ let failure;
2138
+ for (const [serviceName, group] of entries) {
2139
+ this._delegateFor(serviceName).export(group, (result) => {
2140
+ if (result.code !== ExportResultCode.SUCCESS && !failure) {
2141
+ failure = result;
2142
+ }
2143
+ pending -= 1;
2144
+ if (pending === 0) {
2145
+ resultCallback(failure ?? { code: ExportResultCode.SUCCESS });
2146
+ }
2147
+ });
2148
+ }
2149
+ }
2045
2150
  async shutdown() {
2046
- return this._delegate.shutdown();
2151
+ await Promise.all([
2152
+ this._delegate.shutdown(),
2153
+ ...[...this._delegates.values()].map(async (delegate) => delegate.shutdown())
2154
+ ]);
2047
2155
  }
2048
2156
  async forceFlush() {
2049
- return this._delegate.forceFlush?.();
2157
+ await Promise.all([
2158
+ this._delegate.forceFlush?.(),
2159
+ ...[...this._delegates.values()].map(async (delegate) => delegate.forceFlush?.())
2160
+ ]);
2050
2161
  }
2051
2162
  };
2052
2163
 
@@ -2163,7 +2274,14 @@ var TracingModule = class _TracingModule {
2163
2274
  url: tracesUrl,
2164
2275
  headers: config.headers
2165
2276
  });
2166
- this.spanExporter = new BrizzSpanExporter(otlpExporter, config);
2277
+ this.spanExporter = new BrizzSpanExporter(
2278
+ otlpExporter,
2279
+ config,
2280
+ (serviceName) => new OTLPTraceExporter({
2281
+ url: tracesUrl,
2282
+ headers: { ...config.headers, [SERVICE_NAME_HEADER]: serviceName }
2283
+ })
2284
+ );
2167
2285
  logger.debug("OTLP span exporter initialized successfully");
2168
2286
  }
2169
2287
  /**
@@ -2469,6 +2587,7 @@ export {
2469
2587
  callWithMute,
2470
2588
  callWithOrganization,
2471
2589
  callWithProperties,
2590
+ callWithServiceName,
2472
2591
  callWithSessionId,
2473
2592
  callWithUser,
2474
2593
  emitEvent,
@@ -2488,6 +2607,7 @@ export {
2488
2607
  setLogLevel,
2489
2608
  setMessageId,
2490
2609
  setOrganization,
2610
+ setServiceName,
2491
2611
  setSessionId,
2492
2612
  setUser,
2493
2613
  startSession,
@@ -2496,6 +2616,7 @@ export {
2496
2616
  withMute,
2497
2617
  withOrganization,
2498
2618
  withProperties,
2619
+ withServiceName,
2499
2620
  withSessionId,
2500
2621
  withUser
2501
2622
  };
@@ -0,0 +1,12 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+
4
+
5
+ var _chunkQUV5HYJ2cjs = require('./chunk-QUV5HYJ2.cjs');
6
+ require('./chunk-FORVS4QW.cjs');
7
+ require('./chunk-OBGZSXTJ.cjs');
8
+
9
+
10
+
11
+
12
+ exports.InterruptPropagator = _chunkQUV5HYJ2cjs.InterruptPropagator; exports._resetInterruptState = _chunkQUV5HYJ2cjs._resetInterruptState; exports.createInterruptIntegration = _chunkQUV5HYJ2cjs.createInterruptIntegration;
@@ -2,8 +2,8 @@ import {
2
2
  InterruptPropagator,
3
3
  _resetInterruptState,
4
4
  createInterruptIntegration
5
- } from "./chunk-EC3MYSRM.js";
6
- import "./chunk-WII4R5RE.js";
5
+ } from "./chunk-7FQQHF5U.js";
6
+ import "./chunk-Y7NMZAQT.js";
7
7
  import "./chunk-3RG5ZIWI.js";
8
8
  export {
9
9
  InterruptPropagator,
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  getSDKVersion
3
- } from "./chunk-BGLKBQ6N.js";
3
+ } from "./chunk-KVOGOKOB.js";
4
4
  import {
5
5
  logger
6
6
  } from "./chunk-Y4HNUX3Q.js";
@@ -8,7 +8,7 @@ import {
8
8
  BRIZZ,
9
9
  PROPERTIES_CONTEXT_KEY,
10
10
  SESSION_ID
11
- } from "./chunk-WII4R5RE.js";
11
+ } from "./chunk-Y7NMZAQT.js";
12
12
  import "./chunk-3RG5ZIWI.js";
13
13
 
14
14
  // src/internal/instrumentation/mcp/instrumentation.ts
@@ -77,9 +77,6 @@ function safeStringify(value) {
77
77
  }
78
78
  }
79
79
  function emitSchemaSpansFromListResponse(result, transportSessionId, tracer) {
80
- if (!transportSessionId) {
81
- return;
82
- }
83
80
  const tools = extractTools(result);
84
81
  if (tools === void 0) {
85
82
  return;
@@ -112,7 +109,9 @@ function stampSchemaAttributes(span, toolName, transportSessionId, tool) {
112
109
  const outputSchema = tool.outputSchema !== void 0 && tool.outputSchema !== null ? truncateSchemaAttr(safeStringify(tool.outputSchema)) : "";
113
110
  span.setAttribute(RPC_SYSTEM, RPC_SYSTEM_MCP);
114
111
  span.setAttribute(MCP_COMPONENT_TYPE, MCP_COMPONENT_TOOL_SCHEMA);
115
- span.setAttribute(MCP_SESSION_ID, transportSessionId);
112
+ if (transportSessionId) {
113
+ span.setAttribute(MCP_SESSION_ID, transportSessionId);
114
+ }
116
115
  span.setAttribute(MCP_TOOL_NAME, toolName);
117
116
  span.setAttribute(MCP_TOOL_SCHEMA_PARAMETERS, parameters);
118
117
  span.setAttribute(MCP_TOOL_SCHEMA_OUTPUT, outputSchema);
@@ -142,12 +141,20 @@ function generateSessionId() {
142
141
  }
143
142
  return id;
144
143
  }
144
+ function isSessionCarrier(value) {
145
+ return typeof value === "object" && value !== null;
146
+ }
147
+ function resolveTransportSessionId(protocol) {
148
+ if (!isSessionCarrier(protocol)) {
149
+ return void 0;
150
+ }
151
+ return protocol.sessionId ?? protocol._transport?.sessionId;
152
+ }
145
153
  function resolveSessionId(protocol, baseContext) {
146
- if (typeof protocol !== "object" || protocol === null) {
154
+ if (!isSessionCarrier(protocol)) {
147
155
  return void 0;
148
156
  }
149
- const carrier = protocol;
150
- const fromTransport = carrier.sessionId ?? carrier._transport?.sessionId;
157
+ const fromTransport = resolveTransportSessionId(protocol);
151
158
  if (fromTransport) {
152
159
  return fromTransport;
153
160
  }
@@ -158,8 +165,8 @@ function resolveSessionId(protocol, baseContext) {
158
165
  }
159
166
  } catch {
160
167
  }
161
- carrier[FALLBACK_SESSION_ID] ??= generateSessionId();
162
- return carrier[FALLBACK_SESSION_ID];
168
+ protocol[FALLBACK_SESSION_ID] ??= generateSessionId();
169
+ return protocol[FALLBACK_SESSION_ID];
163
170
  }
164
171
  function stampAndPropagateSession(span, sessionId, baseContext = context.active()) {
165
172
  if (!sessionId) {
@@ -449,19 +456,30 @@ function wrapOnRequest(original, tracer) {
449
456
  return original.apply(this, args);
450
457
  }
451
458
  const { span, spanCtx } = started;
452
- const transportSessionId = started.sessionId ?? void 0;
453
- const postResult = method === METHOD_TOOLS_LIST ? (result) => {
454
- try {
455
- emitSchemaSpansFromListResponse(result, transportSessionId, tracer);
456
- } catch (error) {
457
- logger.warn(
458
- `Brizz MCP: failed to emit tools/list schema spans: ${String(error)}`
459
- );
460
- }
461
- } : void 0;
459
+ const hooks = {};
460
+ if (method === METHOD_TOOLS_LIST) {
461
+ hooks.onResult = (result) => {
462
+ try {
463
+ emitSchemaSpansFromListResponse(
464
+ result,
465
+ resolveTransportSessionId(this),
466
+ tracer
467
+ );
468
+ } catch (error) {
469
+ logger.warn(
470
+ `Brizz MCP: failed to emit tools/list schema spans: ${String(error)}`
471
+ );
472
+ }
473
+ };
474
+ }
475
+ if (method !== METHOD_TOOLS_CALL) {
476
+ hooks.onError = () => {
477
+ stampAndPropagateSession(span, resolveSessionId(this, spanCtx), spanCtx);
478
+ };
479
+ }
462
480
  const wrappedHandler = (req, extra) => context2.with(
463
481
  spanCtx,
464
- () => executeHandler(span, method, handler, req, extra, postResult)
482
+ () => executeHandler(span, method, handler, req, extra, hooks)
465
483
  );
466
484
  const hadEntry = handlers.has(method);
467
485
  const prev = handlers.get(method);
@@ -485,41 +503,39 @@ function wrapOnRequest(original, tracer) {
485
503
  }
486
504
  };
487
505
  }
488
- function executeAroundSpan(span, method, run, postResult) {
506
+ function executeAroundSpan(span, method, run, hooks) {
489
507
  let result;
490
508
  try {
491
509
  result = run();
492
510
  } catch (error) {
493
511
  safeApplyErrorAttributes(span, error);
512
+ hooks?.onError?.();
494
513
  safeEnd(span);
495
514
  throw error;
496
515
  }
497
516
  if (!isThenable(result)) {
498
517
  safeApplyResultAttributes(span, method, result);
499
- if (postResult) {
500
- postResult(result);
501
- }
518
+ hooks?.onResult?.(result);
502
519
  safeEnd(span);
503
520
  return result;
504
521
  }
505
522
  return result.then(
506
523
  (value) => {
507
524
  safeApplyResultAttributes(span, method, value);
508
- if (postResult) {
509
- postResult(value);
510
- }
525
+ hooks?.onResult?.(value);
511
526
  safeEnd(span);
512
527
  return value;
513
528
  },
514
529
  (error) => {
515
530
  safeApplyErrorAttributes(span, error);
531
+ hooks?.onError?.();
516
532
  safeEnd(span);
517
533
  throw error;
518
534
  }
519
535
  );
520
536
  }
521
- function executeHandler(span, method, handler, req, extra, postResult) {
522
- return executeAroundSpan(span, method, () => handler(req, extra), postResult);
537
+ function executeHandler(span, method, handler, req, extra, hooks) {
538
+ return executeAroundSpan(span, method, () => handler(req, extra), hooks);
523
539
  }
524
540
  function safeStartClientSpan(tracer, request, protocol) {
525
541
  try {
@@ -546,9 +562,9 @@ function safeStartServerSpan(tracer, request, protocol) {
546
562
  parentCtx
547
563
  );
548
564
  applyServerRequestAttributes(span, request, protocol);
549
- const resolved = resolveSessionId(protocol, parentCtx);
550
- const { context: sessCtx, sessionId } = stampAndPropagateSession(span, resolved, parentCtx);
551
- return { span, spanCtx: trace.setSpan(sessCtx, span), sessionId };
565
+ const resolved = request.method === METHOD_TOOLS_CALL ? resolveSessionId(protocol, parentCtx) : void 0;
566
+ const { context: sessCtx } = stampAndPropagateSession(span, resolved, parentCtx);
567
+ return { span, spanCtx: trace.setSpan(sessCtx, span) };
552
568
  } catch (error) {
553
569
  logger.debug(`Brizz MCP: failed to open SERVER span: ${String(error)}`);
554
570
  return null;