m2m-market 2.2.0 → 2.4.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
@@ -99,6 +99,64 @@ try {
99
99
  console.log(await M2MConnectionClient.fromEnvironment().testConnection());
100
100
  ```
101
101
 
102
+ ## Buy an x402 resource
103
+
104
+ M2M can buy resources listed in the x402 Bazaar for your Agent. M2M pays the
105
+ seller in USDC on Base and charges your Agent's M2M balance, within the limits
106
+ M2M sets for your account. Search matches whole words.
107
+
108
+ ```js
109
+ const found = await client.searchExternal("supported chains rpcs explorers", { limit: 10 });
110
+ const listing = found.listings[0]; // candidate_id, name, price_usdc_base_units, resource_url
111
+
112
+ const result = await client.purchaseExternal(listing.candidate_id);
113
+ console.log(result.purchase.status, result.purchase.response);
114
+ ```
115
+
116
+ Keep `result.idempotency_key`. If the result is `pending`, call
117
+ `purchaseExternal(candidateId, { idempotencyKey })` again with the same key
118
+ to get the outcome. The same key is never paid twice. Reusing a key with a
119
+ different method, body or query is refused with `idempotency_key_conflict` (409).
120
+
121
+ ### GET and POST listings
122
+
123
+ Each listing's `consumption` block has the `method` (GET or POST today) and an
124
+ `input` summary: `body_type`, `body_required`, `has_body_schema`,
125
+ `has_query_schema`, `schema_coverage`. M2M always uses the listing's method.
126
+ `method` is optional and must match it.
127
+
128
+ ```js
129
+ // GET with query parameters
130
+ await client.purchaseExternal(listing.candidate_id, { query: { chain: "base" } });
131
+
132
+ // POST with a JSON body
133
+ await client.purchaseExternal(listing.candidate_id, {
134
+ body: { text: "hello", lang: "en" },
135
+ });
136
+ ```
137
+
138
+ Put sensitive values in `body`, not `query`. Query values are stored with the
139
+ purchase record; only a hash of the body is stored. Calls with no `method`,
140
+ `body` or `query` send the same request as before.
141
+
142
+ ### Refusals and rejected requests
143
+
144
+ Input is checked against the listing's schema before anything is signed or
145
+ charged. A refusal rejects the promise and nothing is charged. The reason code
146
+ is in the error payload: `candidate_not_consumable`, `method_unknown`,
147
+ `method_unsupported`, `method_mismatch`, `body_not_accepted`,
148
+ `body_type_unsupported`, `input_required`, `input_invalid` (with a `fields` list
149
+ of `path` and `code`), `input_too_large` (413) and `query_conflict`.
150
+
151
+ If the seller refuses the paid request, `purchase.status` is
152
+ `paid_request_rejected`, with `http_status`, `method` and
153
+ `rejection: { http_status, reason }`. The reason is one of `bad_request`,
154
+ `unauthorized`, `payment_required`, `forbidden`, `not_found`,
155
+ `method_not_allowed`, `payload_too_large`, `unsupported_media_type`,
156
+ `unprocessable_input`, `rate_limited`, `seller_error` or `other_non_2xx`. The
157
+ request is not retried and the charge is held for review
158
+ (`charge_policy: "retained_pending_review"`).
159
+
102
160
  ## OpenAI-compatible tool
103
161
 
104
162
  ```bash
package/index.d.ts CHANGED
@@ -46,6 +46,19 @@ export interface ExecuteTaskOptions extends Omit<SubmitOptions, "attemptNumber"
46
46
  queryTimeoutMs?: number;
47
47
  }
48
48
 
49
+ export type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };
50
+
51
+ export interface PurchaseExternalOptions {
52
+ /** Reuse the same key to fetch a pending result. A key reused with a different request is refused (409). */
53
+ idempotencyKey?: string;
54
+ /** Must match the listing's method (`consumption.method`). Optional. */
55
+ method?: string;
56
+ /** JSON request body for POST listings. Omit (undefined) to send no body. Put sensitive values here, not in `query`. */
57
+ body?: JsonValue;
58
+ /** Query parameters merged into the listing URL. */
59
+ query?: Record<string, string | number | boolean | Array<string | number | boolean>>;
60
+ }
61
+
49
62
  export interface DiscoverOptions {
50
63
  category?: string;
51
64
  intent?: string;
@@ -70,6 +83,10 @@ export class M2MConnectionClient {
70
83
  submit(options: SubmitOptions): Promise<JsonObject>;
71
84
  /** Preview matching services without reserving funds or invoking a Provider. */
72
85
  discover(options?: DiscoverOptions): Promise<JsonObject>;
86
+ /** Buy one external x402 Bazaar resource for this Agent. Reuse idempotencyKey to fetch a pending result. */
87
+ /** Find x402 Bazaar resources M2M can buy for this Agent (read-only). */
88
+ searchExternal(intent: string, options?: { limit?: number; cursor?: string }): Promise<JsonObject>;
89
+ purchaseExternal(candidateId: string, options?: PurchaseExternalOptions): Promise<JsonObject>;
73
90
  /** Evidence only; does not change settlement, reputation or ranking. */
74
91
  submitAcceptance(queryId: string, options: { acceptanceId: string; accepted: boolean }): Promise<JsonObject>;
75
92
  getQueryStatus(queryId: string): Promise<JsonObject>;
package/index.js CHANGED
@@ -171,6 +171,46 @@ export class M2MConnectionClient {
171
171
  return result.discovery;
172
172
  }
173
173
 
174
+ /**
175
+ * Buy one external x402 resource (an x402 Bazaar discovery candidate) for this Agent.
176
+ * M2M pays the seller in USDC on Base and charges the Agent's M2M balance within M2M's limits.
177
+ * Keep the returned idempotencyKey: if the result is pending, call again with the same key.
178
+ * The same key is never paid twice.
179
+ */
180
+ /** Find x402 Bazaar resources M2M can buy for this Agent (read-only). Search matches whole words. */
181
+ searchExternal(intent, { limit = 10, cursor } = {}) {
182
+ if (!String(intent || "").trim()) throw new Error("intent is required");
183
+ const body = { intent: String(intent).trim(), limit };
184
+ if (cursor) body.cursor = cursor;
185
+ return this.request("POST", "/connect/x402/search", body);
186
+ }
187
+
188
+ /**
189
+ * Optional request fields, sent only when supplied (a call without them sends the same JSON as before):
190
+ * method (must match the listing), body (any JSON value, undefined means no body) and query (object).
191
+ * Put sensitive values in the body, not the query. The server validates all of them before anything is paid.
192
+ */
193
+ async purchaseExternal(candidateId, { idempotencyKey, method, body, query } = {}) {
194
+ const key = String(idempotencyKey || randomUUID());
195
+ if (key.length < 8 || key.length > 128) throw new Error("idempotencyKey must be 8-128 characters");
196
+ if (!String(candidateId || "").trim()) throw new Error("candidateId is required");
197
+ if (method !== undefined && method !== null && (typeof method !== "string" || !method.trim())) {
198
+ throw new TypeError("method must be a non-empty string");
199
+ }
200
+ if (query !== undefined && query !== null && (typeof query !== "object" || Array.isArray(query))) {
201
+ throw new TypeError("query must be an object");
202
+ }
203
+ const payload = {
204
+ candidate_id: String(candidateId).trim(),
205
+ idempotency_key: key,
206
+ };
207
+ if (method !== undefined && method !== null) payload.method = method.trim().toUpperCase();
208
+ if (body !== undefined) payload.body = body;
209
+ if (query !== undefined && query !== null) payload.query = query;
210
+ const result = await this.request("POST", "/connect/x402/purchase", payload);
211
+ return { idempotency_key: key, ...result };
212
+ }
213
+
174
214
  /** Evidence only: does not change settlement, reputation or ranking. */
175
215
  submitAcceptance(queryId, { acceptanceId, accepted } = {}) {
176
216
  if (typeof accepted !== "boolean") throw new TypeError("accepted must be a boolean");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "m2m-market",
3
- "version": "2.2.0",
3
+ "version": "2.4.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.2.0' });
35
+ const client = new sdk.Client({ name: 'm2m-market', version: '2.4.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