m2m-market 2.6.0 → 2.7.0

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
@@ -165,6 +165,21 @@ the payment did settle, marked `reconciled_settled` and the charge stands.
165
165
 
166
166
  `searchExternal` and `purchaseExternal` are deprecated. They still work and warn.
167
167
 
168
+ ## Timing
169
+ Each purchase result has `timing` (milliseconds), so you can see where time went:
170
+
171
+ | Field | Meaning |
172
+ |---|---|
173
+ | `timing.agent.call_total_ms`, `call_ttfb_ms`, `call_ttlb_ms` | Measured by this SDK on your machine: the whole call, time to the first response byte, time to the last byte. Native purchases also have `submit_to_terminal_ms` and `poll_interval_ms`. |
174
+ | `timing.m2m.request_ms`, `response_ms`, `total_ms` | M2M latency: M2M's time before calling the provider, after the provider answered, and both together. |
175
+ | `timing.provider` | M2M's call to the provider: `dns_ms`, `connect_ms` (one network round trip, also `rtt_ms`), `tls_ms`, `sent_ms`, `ttfb_ms` and `ttlb_ms` from the start of the call, the HTTP `status`, and `processing_ms_est` (an estimate of the provider's own processing time). |
176
+
177
+ After a purchase the SDK reports its own figures to M2M without awaiting, so your
178
+ dashboard can also show your network round trip to M2M. The report never delays or
179
+ changes a purchase. It is on by default with the global `fetch`; turn it off with
180
+ `new M2MConnectionClient({ ..., reportTiming: false })`. With your own `fetchImpl`
181
+ it is off unless you pass `reportTiming: true`. A dry run is not reported.
182
+
168
183
  ## OpenAI-compatible tool
169
184
 
170
185
  ```bash
package/index.d.ts CHANGED
@@ -21,6 +21,8 @@ export interface M2MConnectionClientOptions {
21
21
  connectionToken: string;
22
22
  timeoutMs?: number;
23
23
  fetchImpl?: typeof fetch;
24
+ /** Report this SDK's own timing to M2M after a purchase (best effort). Default: true with the global fetch, false with a custom fetchImpl. */
25
+ reportTiming?: boolean;
24
26
  }
25
27
 
26
28
  export interface SubmitOptions {
@@ -148,3 +150,21 @@ export * from "./procurement.js";
148
150
  export * from "./protocols.js";
149
151
  export * from "./procurement-adapters.js";
150
152
  export * from "./commercial.js";
153
+
154
+ /** Timing of one purchase: M2M latency, the provider leg and this Agent's own figures (ms). */
155
+ export interface TransactionTiming {
156
+ v: 1;
157
+ m2m: { request_ms: number | null; response_ms: number | null; total_ms: number | null } | null;
158
+ provider: {
159
+ status: number | null; dns_ms: number | null; connect_ms: number | null; tls_ms: number | null;
160
+ sent_ms: number | null; ttfb_ms: number | null; ttlb_ms: number | null; rtt_ms: number | null;
161
+ processing_ms_est: number | null; error: string | null;
162
+ } | null;
163
+ agent?: {
164
+ call_total_ms?: number; call_ttfb_ms?: number; call_ttlb_ms?: number;
165
+ submit_to_terminal_ms?: number; poll_interval_ms?: number;
166
+ rtt_ms?: number | null; waiting_for_result_ms?: number | null;
167
+ } | null;
168
+ }
169
+
170
+ export const SDK_VERSION: string;
package/index.js CHANGED
@@ -48,17 +48,33 @@ function finishExternal(result, candidateId, key, options, attempts) {
48
48
  return out;
49
49
  }
50
50
 
51
+ export const SDK_VERSION = "2.7.0";
52
+
53
+ const ms = (value) => Math.max(0, Math.round(value));
54
+
55
+ /** result.timing: M2M's view from the response plus this SDK's own figures. */
56
+ function mergeTiming(result, local) {
57
+ if (!local || Object.keys(local).length === 0) return;
58
+ const server = result.timing && typeof result.timing === "object" ? result.timing : {};
59
+ result.timing = { ...server, agent: { ...(server.agent || {}), ...local } };
60
+ }
61
+
51
62
  export class M2MConnectionClient {
52
63
  constructor({
53
64
  connectionToken,
54
65
  baseUrl = DEFAULT_API_BASE_URL,
55
66
  timeoutMs = 30000,
56
- fetchImpl = globalThis.fetch,
67
+ fetchImpl,
68
+ reportTiming,
57
69
  } = {}) {
58
70
  this.baseUrl = String(baseUrl || DEFAULT_API_BASE_URL).replace(/\/$/, "");
59
71
  this.connectionToken = String(connectionToken || "").trim();
60
72
  this.timeoutMs = Math.max(Number(timeoutMs || 30000), 1000);
61
- this.fetchImpl = fetchImpl;
73
+ this.fetchImpl = fetchImpl ?? globalThis.fetch;
74
+ // Send this SDK's own timing to M2M after a purchase (best effort, never awaited).
75
+ // On by default with the global fetch; off with a custom fetchImpl unless asked for.
76
+ this.reportTiming = reportTiming === undefined ? fetchImpl === undefined : Boolean(reportTiming);
77
+ this._lastTiming = {};
62
78
  if (!this.baseUrl.startsWith("https://")) {
63
79
  throw new TypeError("M2M connection base URL must use HTTPS");
64
80
  }
@@ -81,6 +97,7 @@ export class M2MConnectionClient {
81
97
  async request(method, path, body) {
82
98
  const controller = new AbortController();
83
99
  const timer = setTimeout(() => controller.abort(), this.timeoutMs);
100
+ const started = performance.now();
84
101
  try {
85
102
  const response = await this.fetchImpl(`${this.baseUrl}${path}`, {
86
103
  method,
@@ -93,7 +110,14 @@ export class M2MConnectionClient {
93
110
  body: body === undefined ? undefined : JSON.stringify(body),
94
111
  signal: controller.signal,
95
112
  });
113
+ const headersAt = performance.now();
96
114
  const payload = await response.json().catch(() => ({ error: "Invalid API response" }));
115
+ const done = performance.now();
116
+ this._lastTiming = {
117
+ call_total_ms: ms(done - started),
118
+ call_ttfb_ms: ms(headersAt - started),
119
+ call_ttlb_ms: ms(done - started),
120
+ };
97
121
  if (!response.ok) {
98
122
  const ErrorClass = payload && payload.code === "no_matching_service"
99
123
  ? M2MNoMatchingServiceError
@@ -115,6 +139,28 @@ export class M2MConnectionClient {
115
139
  }
116
140
  }
117
141
 
142
+ /** Report this SDK's timing for one transaction. Fire-and-forget; never throws or delays. */
143
+ _sendTiming(target, agent) {
144
+ if (!this.reportTiming || !agent || agent.call_total_ms === undefined) return;
145
+ const controller = new AbortController();
146
+ const timer = setTimeout(() => controller.abort(), 2000);
147
+ if (typeof timer.unref === "function") timer.unref();
148
+ Promise.resolve()
149
+ .then(() => this.fetchImpl(`${this.baseUrl}/connect/timing`, {
150
+ method: "POST",
151
+ headers: {
152
+ Accept: "application/json",
153
+ "Content-Type": "application/json",
154
+ Authorization: `Bearer ${this.connectionToken}`,
155
+ "X-Request-Id": randomUUID(),
156
+ },
157
+ body: JSON.stringify({ ...target, agent: { ...agent, sdk: `node ${SDK_VERSION}` } }),
158
+ signal: controller.signal,
159
+ }))
160
+ .catch(() => {})
161
+ .finally(() => clearTimeout(timer));
162
+ }
163
+
118
164
  testConnection() {
119
165
  return this.request("POST", "/connect/test", {});
120
166
  }
@@ -296,7 +342,11 @@ export class M2MConnectionClient {
296
342
  if (Object.prototype.hasOwnProperty.call(values, "body")) options.body = values.body;
297
343
  if (values.query && typeof values.query === "object" && !Array.isArray(values.query)) options.query = values.query;
298
344
  const result = await this._purchaseExternal(pinned, options);
299
- return finishExternal(result, pinned, callKey, options, []);
345
+ const local = { ...this._lastTiming };
346
+ const out = finishExternal(result, pinned, callKey, options, []);
347
+ mergeTiming(out, local);
348
+ if (!dryRun) this._sendTiming({ idempotency_key: callKey }, local);
349
+ return out;
300
350
  }
301
351
 
302
352
  const found = await this._searchExternal(text, { limit });
@@ -363,7 +413,10 @@ export class M2MConnectionClient {
363
413
  refused.push(describe(entry, (error.payload || {}).fields || []));
364
414
  continue;
365
415
  }
416
+ const local = { ...this._lastTiming };
366
417
  const out = finishExternal(result, cid, key, options, attempts);
418
+ mergeTiming(out, local);
419
+ if (!dryRun) this._sendTiming({ idempotency_key: key }, local);
367
420
  if (dryRun) {
368
421
  out.alternatives = ranked.filter((item) => item.listing.candidate_id !== cid).slice(0, 5).map((item) => describe(item));
369
422
  }
@@ -448,6 +501,7 @@ export class M2MConnectionClient {
448
501
  let excludedCandidates = [];
449
502
 
450
503
  while (attemptNumber <= maximumAttempts) {
504
+ const submittedAt = performance.now();
451
505
  const accepted = await this.submit({
452
506
  category,
453
507
  intent,
@@ -468,11 +522,20 @@ export class M2MConnectionClient {
468
522
  if (Number.isInteger(serverAttempts) && serverAttempts >= 1) {
469
523
  maximumAttempts = Math.min(maximumAttempts, serverAttempts);
470
524
  }
471
- const terminal = ["settled", "released"].includes(
525
+ const submitTiming = { ...this._lastTiming };
526
+ let terminal = ["settled", "released"].includes(
472
527
  String(accepted.lifecycle_state || "").toLowerCase(),
473
528
  )
474
529
  ? accepted
475
530
  : await this.waitForQuery(accepted.query_id, { timeoutMs: queryTimeoutMs });
531
+ const local = {
532
+ ...submitTiming,
533
+ submit_to_terminal_ms: ms(performance.now() - submittedAt),
534
+ poll_interval_ms: 1000,
535
+ };
536
+ terminal = { ...terminal };
537
+ mergeTiming(terminal, local);
538
+ if (terminal.query_id) this._sendTiming({ query_id: String(terminal.query_id) }, local);
476
539
 
477
540
  attempts.push({
478
541
  attempt_number: attemptNumber,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "m2m-market",
3
- "version": "2.6.0",
3
+ "version": "2.7.0",
4
4
  "description": "Customer SDK for connecting AI Agents to M2M Market",
5
5
  "author": "M2M Market, Inc.",
6
6
  "type": "module",
package/protocols.js CHANGED
@@ -32,7 +32,7 @@ export async function connectMcp({ accessToken, timeoutMs = 30000, fetchImpl = g
32
32
  const transport = new sdk.StreamableHTTPClientTransport(new URL(MCP_RESOURCE), {
33
33
  fetch: guardedFetch, reconnectionOptions: { maxRetries: 0, initialReconnectionDelay: 1000, maxReconnectionDelay: 1000, reconnectionDelayGrowFactor: 1 }
34
34
  });
35
- const client = new sdk.Client({ name: 'm2m-market', version: '2.6.0' });
35
+ const client = new sdk.Client({ name: 'm2m-market', version: '2.7.0' });
36
36
  try { await client.connect(transport); }
37
37
  catch { await client.close().catch(() => {}); throw new M2MAPIError('mcp_connection_failed'); }
38
38
  return client; // caller closes it in finally; no automatic paid call or replay