m2m-market 2.0.0 → 2.1.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
@@ -52,7 +52,33 @@ const result = await client.executeTask({
52
52
  console.log(result.response);
53
53
  ```
54
54
 
55
- ## Test the connection
55
+ ## Ask for an outcome
56
+
57
+ ```js
58
+ import { M2MConnectionClient, M2MNoMatchingServiceError } from "m2m-market";
59
+
60
+ const client = M2MConnectionClient.fromEnvironment();
61
+ const request = {
62
+ intent: "current weather in Nairobi",
63
+ payload: { city: "Nairobi" },
64
+ requiredCapabilities: ["current_weather"],
65
+ expect: ["temperature_c"],
66
+ maximumPriceM2m: "0.05",
67
+ maximumAttempts: 3, // 1-5; the dashboard policy may lower it
68
+ };
69
+
70
+ // Preview first: no funds are reserved and no Provider is called.
71
+ console.log(await client.discover(request));
72
+
73
+ try {
74
+ const result = await client.purchase(request);
75
+ console.log(result.response, result.attempts_limited_by_authorization);
76
+ await client.submitAcceptance(result.query_id, { acceptanceId: "job-42", accepted: true }); // evidence only
77
+ } catch (error) {
78
+ if (!(error instanceof M2MNoMatchingServiceError)) throw error;
79
+ // Nothing was paid; relax the request or pick another category.
80
+ }
81
+ ```
56
82
 
57
83
  ```js
58
84
  console.log(await M2MConnectionClient.fromEnvironment().testConnection());
package/adapters.js CHANGED
@@ -15,7 +15,27 @@ export function openAIToolDefinition() {
15
15
  properties: {
16
16
  category: {
17
17
  type: "string",
18
- description: "Marketplace service category, such as traffic-data.",
18
+ description: "Marketplace service category, such as weather_climate. Provide this or intent.",
19
+ },
20
+ intent: {
21
+ type: "string",
22
+ description: "Plain-language outcome needed, such as 'current weather in Nairobi'. Provide this or category.",
23
+ },
24
+ required_capabilities: {
25
+ type: "array",
26
+ items: { type: "string" },
27
+ description: "Capabilities the service must advertise, such as current_weather.",
28
+ },
29
+ expect: {
30
+ type: "array",
31
+ items: { type: "string" },
32
+ description: "Output fields the result must contain, such as temperature_c.",
33
+ },
34
+ maximum_attempts: {
35
+ type: "integer",
36
+ minimum: 1,
37
+ maximum: 5,
38
+ description: "Provider attempts allowed if a provider fails; the dashboard policy may lower it.",
19
39
  },
20
40
  payload: {
21
41
  type: "object",
@@ -33,7 +53,7 @@ export function openAIToolDefinition() {
33
53
  description: "Optional stricter minimum Provider reputation.",
34
54
  },
35
55
  },
36
- required: ["category", "payload"],
56
+ required: ["payload"],
37
57
  additionalProperties: false,
38
58
  },
39
59
  },
@@ -51,23 +71,31 @@ export class M2MToolAdapter {
51
71
 
52
72
  async invoke({
53
73
  category,
54
- payload,
74
+ intent,
75
+ payload = {},
76
+ required_capabilities,
77
+ expect,
78
+ maximum_attempts,
55
79
  maximum_price_m2m,
56
80
  minimum_reputation,
57
81
  }) {
58
- const result = await this.client.executeTask({
82
+ const result = await this.client.purchase({
59
83
  category,
84
+ intent,
60
85
  payload,
86
+ requiredCapabilities: required_capabilities ?? this.defaultPolicy.requiredCapabilities,
87
+ integrationTypes: this.defaultPolicy.integrationTypes,
88
+ expect: expect ?? this.defaultPolicy.expect,
61
89
  maximumPriceM2m:
62
90
  maximum_price_m2m ?? this.defaultPolicy.maximumPriceM2m,
63
91
  minimumReputation:
64
92
  minimum_reputation ?? this.defaultPolicy.minimumReputation,
65
- maximumAttempts: this.defaultPolicy.maximumAttempts ?? 1,
93
+ maximumAttempts: maximum_attempts ?? this.defaultPolicy.maximumAttempts ?? 1,
66
94
  responseFormat: this.defaultPolicy.responseFormat ?? "JSON",
67
95
  });
68
96
  return {
69
97
  status: result.status,
70
- category,
98
+ category: category || intent,
71
99
  provider_id: result.provider_id,
72
100
  service_id: result.service_id,
73
101
  result: result.response,
@@ -105,8 +133,12 @@ export class M2MToolAdapter {
105
133
  name: M2M_TOOL_NAME,
106
134
  description: M2M_TOOL_DESCRIPTION,
107
135
  schema: z.object({
108
- category: z.string().min(1),
136
+ category: z.string().min(1).optional(),
137
+ intent: z.string().min(1).optional(),
109
138
  payload: z.object({}).catchall(z.unknown()),
139
+ required_capabilities: z.array(z.string()).optional(),
140
+ expect: z.array(z.string()).optional(),
141
+ maximum_attempts: z.number().int().min(1).max(5).optional(),
110
142
  maximum_price_m2m: z.string().optional(),
111
143
  minimum_reputation: z.number().int().min(0).max(100).optional(),
112
144
  }),
package/index.d.ts CHANGED
@@ -13,6 +13,9 @@ export class M2MConnectionError extends Error {
13
13
  constructor(message: string, options?: M2MConnectionErrorOptions);
14
14
  }
15
15
 
16
+ /** No validated service matches the request; nothing was reserved or paid. */
17
+ export class M2MNoMatchingServiceError extends M2MConnectionError {}
18
+
16
19
  export interface M2MConnectionClientOptions {
17
20
  baseUrl?: string;
18
21
  connectionToken: string;
@@ -21,8 +24,14 @@ export interface M2MConnectionClientOptions {
21
24
  }
22
25
 
23
26
  export interface SubmitOptions {
24
- category: string;
27
+ /** Provide category, intent, or both. */
28
+ category?: string;
29
+ intent?: string;
25
30
  payload: JsonObject;
31
+ requiredCapabilities?: string[];
32
+ integrationTypes?: string[];
33
+ /** Output fields the result must contain. */
34
+ expect?: string[];
26
35
  maximumPriceM2m?: string | number;
27
36
  minimumReputation?: number;
28
37
  maximumAttempts?: number;
@@ -36,6 +45,19 @@ export interface ExecuteTaskOptions extends Omit<SubmitOptions, "attemptNumber"
36
45
  queryTimeoutMs?: number;
37
46
  }
38
47
 
48
+ export interface DiscoverOptions {
49
+ category?: string;
50
+ intent?: string;
51
+ payload?: JsonObject;
52
+ requiredCapabilities?: string[];
53
+ integrationTypes?: string[];
54
+ expect?: string[];
55
+ maximumPriceM2m?: string | number;
56
+ minimumReputation?: number;
57
+ responseFormat?: string;
58
+ limit?: number;
59
+ }
60
+
39
61
  export class M2MConnectionClient {
40
62
  baseUrl: string;
41
63
  connectionToken: string;
@@ -45,6 +67,10 @@ export class M2MConnectionClient {
45
67
  request(method: string, path: string, body?: JsonObject): Promise<JsonObject>;
46
68
  testConnection(): Promise<JsonObject>;
47
69
  submit(options: SubmitOptions): Promise<JsonObject>;
70
+ /** Preview matching services without reserving funds or invoking a Provider. */
71
+ discover(options?: DiscoverOptions): Promise<JsonObject>;
72
+ /** Evidence only; does not change settlement, reputation or ranking. */
73
+ submitAcceptance(queryId: string, options: { acceptanceId: string; accepted: boolean }): Promise<JsonObject>;
48
74
  getQueryStatus(queryId: string): Promise<JsonObject>;
49
75
  getTaskStatus(taskId: string): Promise<JsonObject>;
50
76
  waitForQuery(
package/index.js CHANGED
@@ -11,6 +11,13 @@ export class M2MConnectionError extends Error {
11
11
  }
12
12
  }
13
13
 
14
+ export class M2MNoMatchingServiceError extends M2MConnectionError {
15
+ constructor(message, options) {
16
+ super(message, options);
17
+ this.name = "M2MNoMatchingServiceError";
18
+ }
19
+ }
20
+
14
21
  export class M2MConnectionClient {
15
22
  constructor({
16
23
  connectionToken,
@@ -58,7 +65,10 @@ export class M2MConnectionClient {
58
65
  });
59
66
  const payload = await response.json().catch(() => ({ error: "Invalid API response" }));
60
67
  if (!response.ok) {
61
- throw new M2MConnectionError(
68
+ const ErrorClass = payload && payload.code === "no_matching_service"
69
+ ? M2MNoMatchingServiceError
70
+ : M2MConnectionError;
71
+ throw new ErrorClass(
62
72
  payload.error || payload.message || "M2M request failed",
63
73
  { status: response.status, payload },
64
74
  );
@@ -81,7 +91,11 @@ export class M2MConnectionClient {
81
91
 
82
92
  submit({
83
93
  category,
94
+ intent,
84
95
  payload,
96
+ requiredCapabilities,
97
+ integrationTypes,
98
+ expect,
85
99
  maximumPriceM2m,
86
100
  minimumReputation,
87
101
  maximumAttempts,
@@ -90,17 +104,23 @@ export class M2MConnectionClient {
90
104
  attemptNumber = 1,
91
105
  excludedCandidates = [],
92
106
  }) {
93
- if (!String(category || "").trim()) throw new TypeError("Service category is required");
107
+ if (!String(category || "").trim() && !String(intent || "").trim()) {
108
+ throw new TypeError("A service category or an intent is required");
109
+ }
94
110
  if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
95
111
  throw new TypeError("Service payload must be an object");
96
112
  }
97
113
  const body = {
98
- category: String(category).trim(),
99
114
  payload,
100
115
  response_format: responseFormat,
101
116
  attempt_number: Number(attemptNumber),
102
117
  excluded_candidates: [...excludedCandidates],
103
118
  };
119
+ if (String(category || "").trim()) body.category = String(category).trim();
120
+ if (String(intent || "").trim()) body.intent = String(intent).trim();
121
+ if (requiredCapabilities?.length) body.required_capabilities = [...requiredCapabilities];
122
+ if (integrationTypes?.length) body.integration_types = [...integrationTypes];
123
+ if (expect?.length) body.expect = [...expect];
104
124
  if (maximumPriceM2m !== undefined) body.maximum_price_m2m = String(maximumPriceM2m);
105
125
  if (minimumReputation !== undefined) body.minimum_reputation = Number(minimumReputation);
106
126
  if (maximumAttempts !== undefined) body.maximum_attempts = Number(maximumAttempts);
@@ -108,6 +128,50 @@ export class M2MConnectionClient {
108
128
  return this.request("POST", "/connect/execute", body);
109
129
  }
110
130
 
131
+ /** Preview matching services without reserving funds or invoking a Provider. */
132
+ async discover({
133
+ category,
134
+ intent,
135
+ payload,
136
+ requiredCapabilities,
137
+ integrationTypes,
138
+ expect,
139
+ maximumPriceM2m,
140
+ minimumReputation,
141
+ responseFormat = "JSON",
142
+ limit = 10,
143
+ } = {}) {
144
+ if (!String(category || "").trim() && !String(intent || "").trim()) {
145
+ throw new TypeError("A service category or an intent is required");
146
+ }
147
+ if (payload !== undefined && (!payload || typeof payload !== "object" || Array.isArray(payload))) {
148
+ throw new TypeError("Service payload must be an object");
149
+ }
150
+ const body = { response_format: responseFormat, limit: Number(limit) };
151
+ if (String(category || "").trim()) body.category = String(category).trim();
152
+ if (String(intent || "").trim()) body.intent = String(intent).trim();
153
+ if (payload !== undefined) body.payload = payload;
154
+ if (requiredCapabilities?.length) body.required_capabilities = [...requiredCapabilities];
155
+ if (integrationTypes?.length) body.integration_types = [...integrationTypes];
156
+ if (expect?.length) body.expect = [...expect];
157
+ if (maximumPriceM2m !== undefined) body.maximum_price_m2m = String(maximumPriceM2m);
158
+ if (minimumReputation !== undefined) body.minimum_reputation = Number(minimumReputation);
159
+ const result = await this.request("POST", "/connect/discover", body);
160
+ if (!result.discovery || typeof result.discovery !== "object") {
161
+ throw new M2MConnectionError("Discovery response is missing the discovery record");
162
+ }
163
+ return result.discovery;
164
+ }
165
+
166
+ /** Evidence only: does not change settlement, reputation or ranking. */
167
+ submitAcceptance(queryId, { acceptanceId, accepted } = {}) {
168
+ if (typeof accepted !== "boolean") throw new TypeError("accepted must be a boolean");
169
+ return this.request("POST", `/connect/queries/${queryId}/acceptance`, {
170
+ acceptance_id: acceptanceId,
171
+ accepted,
172
+ });
173
+ }
174
+
111
175
  getQueryStatus(queryId) {
112
176
  return this.request("GET", `/connect/queries/${queryId}`);
113
177
  }
@@ -138,7 +202,11 @@ export class M2MConnectionClient {
138
202
 
139
203
  async purchase({
140
204
  category,
205
+ intent,
141
206
  payload,
207
+ requiredCapabilities,
208
+ integrationTypes,
209
+ expect,
142
210
  maximumPriceM2m,
143
211
  minimumReputation,
144
212
  maximumAttempts = 1,
@@ -150,6 +218,10 @@ export class M2MConnectionClient {
150
218
  if (!Number.isInteger(maximumAttempts) || maximumAttempts < 1 || maximumAttempts > 5) {
151
219
  throw new TypeError("Maximum attempts must be between 1 and 5");
152
220
  }
221
+ if (!String(category || "").trim() && !String(intent || "").trim()) {
222
+ throw new TypeError("A service category or an intent is required");
223
+ }
224
+ const requestedAttempts = maximumAttempts;
153
225
 
154
226
  const attempts = [];
155
227
  let attemptNumber = 1;
@@ -158,7 +230,11 @@ export class M2MConnectionClient {
158
230
  while (attemptNumber <= maximumAttempts) {
159
231
  const accepted = await this.submit({
160
232
  category,
233
+ intent,
161
234
  payload,
235
+ requiredCapabilities,
236
+ integrationTypes,
237
+ expect,
162
238
  maximumPriceM2m,
163
239
  minimumReputation,
164
240
  maximumAttempts,
@@ -167,6 +243,11 @@ export class M2MConnectionClient {
167
243
  attemptNumber,
168
244
  excludedCandidates,
169
245
  });
246
+ // The dashboard authorization can lower the attempt limit; honour it.
247
+ const serverAttempts = Number(accepted.maximum_attempts);
248
+ if (Number.isInteger(serverAttempts) && serverAttempts >= 1) {
249
+ maximumAttempts = Math.min(maximumAttempts, serverAttempts);
250
+ }
170
251
  const terminal = ["settled", "released"].includes(
171
252
  String(accepted.lifecycle_state || "").toLowerCase(),
172
253
  )
@@ -183,7 +264,14 @@ export class M2MConnectionClient {
183
264
  });
184
265
 
185
266
  if (String(terminal.lifecycle_state || "").toLowerCase() === "settled") {
186
- return { ...terminal, task_id: taskId, attempts, autonomous_completion: true };
267
+ return {
268
+ ...terminal,
269
+ task_id: taskId,
270
+ attempts,
271
+ requested_attempts: requestedAttempts,
272
+ attempts_limited_by_authorization: maximumAttempts < requestedAttempts,
273
+ autonomous_completion: true,
274
+ };
187
275
  }
188
276
 
189
277
  const task = await this.getTaskStatus(taskId);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "m2m-market",
3
- "version": "2.0.0",
3
+ "version": "2.1.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.0.0' });
35
+ const client = new sdk.Client({ name: 'm2m-market', version: '2.1.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