m2m-market 2.0.0 → 2.2.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,48 @@ const result = await client.executeTask({
52
52
  console.log(result.response);
53
53
  ```
54
54
 
55
- ## Test the connection
55
+ ## Ask in plain language
56
+
57
+ ```js
58
+ const result = await client.ask("I need weather for Nairobi today");
59
+ console.log(result.response);
60
+ ```
61
+
62
+ M2M works out the capability, reads the inputs from the text (here a location
63
+ and a date), maps them onto each Provider's own field names, picks a validated
64
+ Provider and applies the dashboard spending policy. No payload or policy is
65
+ needed. If a required input is missing from the text, the request fails with
66
+ `intent_input_missing` before anything is reserved; add it to the text or pass
67
+ `payload`. `client.discover({ intent })` previews what would be sent
68
+ (`resolved.input` and each candidate's `provider_input`) without spending.
69
+
70
+ ## Ask for an outcome
71
+
72
+ ```js
73
+ import { M2MConnectionClient, M2MNoMatchingServiceError } from "m2m-market";
74
+
75
+ const client = M2MConnectionClient.fromEnvironment();
76
+ const request = {
77
+ intent: "current weather in Nairobi",
78
+ payload: { city: "Nairobi" },
79
+ requiredCapabilities: ["current_weather"],
80
+ expect: ["temperature_c"],
81
+ maximumPriceM2m: "0.05",
82
+ maximumAttempts: 3, // 1-5; the dashboard policy may lower it
83
+ };
84
+
85
+ // Preview first: no funds are reserved and no Provider is called.
86
+ console.log(await client.discover(request));
87
+
88
+ try {
89
+ const result = await client.purchase(request);
90
+ console.log(result.response, result.attempts_limited_by_authorization);
91
+ await client.submitAcceptance(result.query_id, { acceptanceId: "job-42", accepted: true }); // evidence only
92
+ } catch (error) {
93
+ if (!(error instanceof M2MNoMatchingServiceError)) throw error;
94
+ // Nothing was paid; relax the request or pick another category.
95
+ }
96
+ ```
56
97
 
57
98
  ```js
58
99
  console.log(await M2MConnectionClient.fromEnvironment().testConnection());
package/adapters.js CHANGED
@@ -15,11 +15,31 @@ 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 'I need weather for Nairobi today'. M2M reads the inputs from it.",
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",
22
- description: "JSON input sent to the selected Provider service.",
42
+ description: "Optional JSON input. Omit it to let M2M read the inputs from the intent.",
23
43
  additionalProperties: true,
24
44
  },
25
45
  maximum_price_m2m: {
@@ -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: ["intent"],
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),
109
- payload: z.object({}).catchall(z.unknown()),
136
+ category: z.string().min(1).optional(),
137
+ intent: z.string().min(1),
138
+ payload: z.object({}).catchall(z.unknown()).optional(),
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,15 @@ export interface M2MConnectionClientOptions {
21
24
  }
22
25
 
23
26
  export interface SubmitOptions {
24
- category: string;
25
- payload: JsonObject;
27
+ /** Provide category, intent, or both. */
28
+ category?: string;
29
+ intent?: string;
30
+ /** Optional when an intent is given: M2M reads the inputs from the text. */
31
+ payload?: JsonObject;
32
+ requiredCapabilities?: string[];
33
+ integrationTypes?: string[];
34
+ /** Output fields the result must contain. */
35
+ expect?: string[];
26
36
  maximumPriceM2m?: string | number;
27
37
  minimumReputation?: number;
28
38
  maximumAttempts?: number;
@@ -36,6 +46,19 @@ export interface ExecuteTaskOptions extends Omit<SubmitOptions, "attemptNumber"
36
46
  queryTimeoutMs?: number;
37
47
  }
38
48
 
49
+ export interface DiscoverOptions {
50
+ category?: string;
51
+ intent?: string;
52
+ payload?: JsonObject;
53
+ requiredCapabilities?: string[];
54
+ integrationTypes?: string[];
55
+ expect?: string[];
56
+ maximumPriceM2m?: string | number;
57
+ minimumReputation?: number;
58
+ responseFormat?: string;
59
+ limit?: number;
60
+ }
61
+
39
62
  export class M2MConnectionClient {
40
63
  baseUrl: string;
41
64
  connectionToken: string;
@@ -45,6 +68,10 @@ export class M2MConnectionClient {
45
68
  request(method: string, path: string, body?: JsonObject): Promise<JsonObject>;
46
69
  testConnection(): Promise<JsonObject>;
47
70
  submit(options: SubmitOptions): Promise<JsonObject>;
71
+ /** Preview matching services without reserving funds or invoking a Provider. */
72
+ discover(options?: DiscoverOptions): Promise<JsonObject>;
73
+ /** Evidence only; does not change settlement, reputation or ranking. */
74
+ submitAcceptance(queryId: string, options: { acceptanceId: string; accepted: boolean }): Promise<JsonObject>;
48
75
  getQueryStatus(queryId: string): Promise<JsonObject>;
49
76
  getTaskStatus(taskId: string): Promise<JsonObject>;
50
77
  waitForQuery(
@@ -54,6 +81,8 @@ export class M2MConnectionClient {
54
81
  purchase(options: ExecuteTaskOptions): Promise<JsonObject>;
55
82
  /** @deprecated Use purchase. */
56
83
  executeTask(options: ExecuteTaskOptions): Promise<JsonObject>;
84
+ /** Buy an outcome from a plain-language request, e.g. "I need weather for Nairobi today". */
85
+ ask(intent: string, options?: Omit<ExecuteTaskOptions, "intent">): Promise<JsonObject>;
57
86
  }
58
87
 
59
88
  export * from "./procurement.js";
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,31 @@ export class M2MConnectionClient {
90
104
  attemptNumber = 1,
91
105
  excludedCandidates = [],
92
106
  }) {
93
- if (!String(category || "").trim()) throw new TypeError("Service category is required");
94
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
107
+ if (!String(category || "").trim() && !String(intent || "").trim()) {
108
+ throw new TypeError("A service category or an intent is required");
109
+ }
110
+ // Payload is optional with an intent: M2M reads standard inputs from the
111
+ // text and maps them onto each Provider's own field names.
112
+ if (payload === undefined || payload === null) {
113
+ if (!String(intent || "").trim()) {
114
+ throw new TypeError("A payload is required when no intent is given");
115
+ }
116
+ payload = {};
117
+ }
118
+ if (typeof payload !== "object" || Array.isArray(payload)) {
95
119
  throw new TypeError("Service payload must be an object");
96
120
  }
97
121
  const body = {
98
- category: String(category).trim(),
99
122
  payload,
100
123
  response_format: responseFormat,
101
124
  attempt_number: Number(attemptNumber),
102
125
  excluded_candidates: [...excludedCandidates],
103
126
  };
127
+ if (String(category || "").trim()) body.category = String(category).trim();
128
+ if (String(intent || "").trim()) body.intent = String(intent).trim();
129
+ if (requiredCapabilities?.length) body.required_capabilities = [...requiredCapabilities];
130
+ if (integrationTypes?.length) body.integration_types = [...integrationTypes];
131
+ if (expect?.length) body.expect = [...expect];
104
132
  if (maximumPriceM2m !== undefined) body.maximum_price_m2m = String(maximumPriceM2m);
105
133
  if (minimumReputation !== undefined) body.minimum_reputation = Number(minimumReputation);
106
134
  if (maximumAttempts !== undefined) body.maximum_attempts = Number(maximumAttempts);
@@ -108,6 +136,50 @@ export class M2MConnectionClient {
108
136
  return this.request("POST", "/connect/execute", body);
109
137
  }
110
138
 
139
+ /** Preview matching services without reserving funds or invoking a Provider. */
140
+ async discover({
141
+ category,
142
+ intent,
143
+ payload,
144
+ requiredCapabilities,
145
+ integrationTypes,
146
+ expect,
147
+ maximumPriceM2m,
148
+ minimumReputation,
149
+ responseFormat = "JSON",
150
+ limit = 10,
151
+ } = {}) {
152
+ if (!String(category || "").trim() && !String(intent || "").trim()) {
153
+ throw new TypeError("A service category or an intent is required");
154
+ }
155
+ if (payload !== undefined && (!payload || typeof payload !== "object" || Array.isArray(payload))) {
156
+ throw new TypeError("Service payload must be an object");
157
+ }
158
+ const body = { response_format: responseFormat, limit: Number(limit) };
159
+ if (String(category || "").trim()) body.category = String(category).trim();
160
+ if (String(intent || "").trim()) body.intent = String(intent).trim();
161
+ if (payload !== undefined) body.payload = payload;
162
+ if (requiredCapabilities?.length) body.required_capabilities = [...requiredCapabilities];
163
+ if (integrationTypes?.length) body.integration_types = [...integrationTypes];
164
+ if (expect?.length) body.expect = [...expect];
165
+ if (maximumPriceM2m !== undefined) body.maximum_price_m2m = String(maximumPriceM2m);
166
+ if (minimumReputation !== undefined) body.minimum_reputation = Number(minimumReputation);
167
+ const result = await this.request("POST", "/connect/discover", body);
168
+ if (!result.discovery || typeof result.discovery !== "object") {
169
+ throw new M2MConnectionError("Discovery response is missing the discovery record");
170
+ }
171
+ return result.discovery;
172
+ }
173
+
174
+ /** Evidence only: does not change settlement, reputation or ranking. */
175
+ submitAcceptance(queryId, { acceptanceId, accepted } = {}) {
176
+ if (typeof accepted !== "boolean") throw new TypeError("accepted must be a boolean");
177
+ return this.request("POST", `/connect/queries/${queryId}/acceptance`, {
178
+ acceptance_id: acceptanceId,
179
+ accepted,
180
+ });
181
+ }
182
+
111
183
  getQueryStatus(queryId) {
112
184
  return this.request("GET", `/connect/queries/${queryId}`);
113
185
  }
@@ -136,9 +208,23 @@ export class M2MConnectionClient {
136
208
  /** @deprecated Use purchase; Connect failover semantics are unchanged. */
137
209
  executeTask(options) { return this.purchase(options); }
138
210
 
211
+ /**
212
+ * Buy an outcome from a plain-language request, for example
213
+ * `ask("I need weather for Nairobi today")`. M2M resolves the capability,
214
+ * reads the inputs, picks a validated Provider and applies the dashboard policy.
215
+ */
216
+ ask(intent, options = {}) {
217
+ if (!String(intent || "").trim()) throw new TypeError("An intent is required");
218
+ return this.purchase({ ...options, intent: String(intent).trim() });
219
+ }
220
+
139
221
  async purchase({
140
222
  category,
223
+ intent,
141
224
  payload,
225
+ requiredCapabilities,
226
+ integrationTypes,
227
+ expect,
142
228
  maximumPriceM2m,
143
229
  minimumReputation,
144
230
  maximumAttempts = 1,
@@ -150,6 +236,10 @@ export class M2MConnectionClient {
150
236
  if (!Number.isInteger(maximumAttempts) || maximumAttempts < 1 || maximumAttempts > 5) {
151
237
  throw new TypeError("Maximum attempts must be between 1 and 5");
152
238
  }
239
+ if (!String(category || "").trim() && !String(intent || "").trim()) {
240
+ throw new TypeError("A service category or an intent is required");
241
+ }
242
+ const requestedAttempts = maximumAttempts;
153
243
 
154
244
  const attempts = [];
155
245
  let attemptNumber = 1;
@@ -158,7 +248,11 @@ export class M2MConnectionClient {
158
248
  while (attemptNumber <= maximumAttempts) {
159
249
  const accepted = await this.submit({
160
250
  category,
251
+ intent,
161
252
  payload,
253
+ requiredCapabilities,
254
+ integrationTypes,
255
+ expect,
162
256
  maximumPriceM2m,
163
257
  minimumReputation,
164
258
  maximumAttempts,
@@ -167,6 +261,11 @@ export class M2MConnectionClient {
167
261
  attemptNumber,
168
262
  excludedCandidates,
169
263
  });
264
+ // The dashboard authorization can lower the attempt limit; honour it.
265
+ const serverAttempts = Number(accepted.maximum_attempts);
266
+ if (Number.isInteger(serverAttempts) && serverAttempts >= 1) {
267
+ maximumAttempts = Math.min(maximumAttempts, serverAttempts);
268
+ }
170
269
  const terminal = ["settled", "released"].includes(
171
270
  String(accepted.lifecycle_state || "").toLowerCase(),
172
271
  )
@@ -183,7 +282,14 @@ export class M2MConnectionClient {
183
282
  });
184
283
 
185
284
  if (String(terminal.lifecycle_state || "").toLowerCase() === "settled") {
186
- return { ...terminal, task_id: taskId, attempts, autonomous_completion: true };
285
+ return {
286
+ ...terminal,
287
+ task_id: taskId,
288
+ attempts,
289
+ requested_attempts: requestedAttempts,
290
+ attempts_limited_by_authorization: maximumAttempts < requestedAttempts,
291
+ autonomous_completion: true,
292
+ };
187
293
  }
188
294
 
189
295
  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.2.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.2.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