@frontmcp/react 1.8.6 → 1.9.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.
Files changed (47) hide show
  1. package/README.md +2 -0
  2. package/ai/index.js +90 -17
  3. package/api/api.types.d.ts +29 -0
  4. package/api/api.types.d.ts.map +1 -1
  5. package/api/index.d.ts +1 -1
  6. package/api/index.d.ts.map +1 -1
  7. package/api/index.js +136 -33
  8. package/api/parseOpenApiSpec.d.ts.map +1 -1
  9. package/api/useApiClient.d.ts +5 -0
  10. package/api/useApiClient.d.ts.map +1 -1
  11. package/components/ToolForm.d.ts +1 -1
  12. package/components/ToolForm.d.ts.map +1 -1
  13. package/esm/ai/index.mjs +93 -20
  14. package/esm/api/index.mjs +136 -33
  15. package/esm/index.mjs +298 -85
  16. package/esm/package.json +6 -6
  17. package/esm/router/index.mjs +22 -4
  18. package/esm/state/index.mjs +113 -98
  19. package/hooks/useDynamicTool.d.ts +19 -3
  20. package/hooks/useDynamicTool.d.ts.map +1 -1
  21. package/hooks/useServer.d.ts +2 -2
  22. package/hooks/useServer.d.ts.map +1 -1
  23. package/index.d.ts +1 -0
  24. package/index.d.ts.map +1 -1
  25. package/index.js +293 -80
  26. package/package.json +6 -6
  27. package/provider/FrontMcpContext.d.ts +2 -1
  28. package/provider/FrontMcpContext.d.ts.map +1 -1
  29. package/provider/FrontMcpProvider.d.ts +12 -6
  30. package/provider/FrontMcpProvider.d.ts.map +1 -1
  31. package/registry/DynamicRegistry.d.ts +12 -6
  32. package/registry/DynamicRegistry.d.ts.map +1 -1
  33. package/registry/ServerRegistry.d.ts +14 -3
  34. package/registry/ServerRegistry.d.ts.map +1 -1
  35. package/registry/bindDynamicTools.d.ts +29 -0
  36. package/registry/bindDynamicTools.d.ts.map +1 -0
  37. package/registry/createWrappedServer.d.ts +6 -5
  38. package/registry/createWrappedServer.d.ts.map +1 -1
  39. package/router/index.js +22 -4
  40. package/router/router.entries.d.ts +9 -5
  41. package/router/router.entries.d.ts.map +1 -1
  42. package/state/index.js +112 -97
  43. package/state/useReduxResource.d.ts.map +1 -1
  44. package/state/useStoreResource.d.ts +6 -0
  45. package/state/useStoreResource.d.ts.map +1 -1
  46. package/types.d.ts +10 -1
  47. package/types.d.ts.map +1 -1
package/esm/ai/index.mjs CHANGED
@@ -3,7 +3,7 @@ import { useState, useCallback as useCallback2, useEffect } from "react";
3
3
  import { formatToolsForPlatform, formatResultForPlatform } from "@frontmcp/sdk";
4
4
 
5
5
  // libs/react/src/hooks/useResolvedServer.ts
6
- import { useContext } from "react";
6
+ import { useContext as useContext2 } from "react";
7
7
 
8
8
  // libs/react/src/provider/FrontMcpContext.ts
9
9
  import { createContext } from "react";
@@ -62,22 +62,23 @@ var DynamicRegistry = class {
62
62
  toolRefCounts = /* @__PURE__ */ new Map();
63
63
  resourceRefCounts = /* @__PURE__ */ new Map();
64
64
  listeners = /* @__PURE__ */ new Set();
65
+ resourceListeners = /* @__PURE__ */ new Set();
65
66
  version = 0;
66
67
  /**
67
68
  * Register a dynamic tool. Returns an unregister function
68
69
  * suitable for useEffect cleanup.
69
70
  *
70
71
  * Multiple registrations of the same name are ref-counted:
71
- * subsequent registrations update the definition but the tool
72
- * is only removed when every registrant has unregistered.
72
+ * subsequent registrations replace the definition (and notify, so
73
+ * the server registration follows the new description, schema or
74
+ * availability) but the tool is only removed when every registrant
75
+ * has unregistered.
73
76
  */
74
77
  registerTool(def) {
75
78
  const existing = this.toolRefCounts.get(def.name) ?? 0;
76
79
  this.toolRefCounts.set(def.name, existing + 1);
77
80
  this.tools.set(def.name, def);
78
- if (existing === 0) {
79
- this.notify();
80
- }
81
+ this.notify();
81
82
  let called = false;
82
83
  return () => {
83
84
  if (called) return;
@@ -140,8 +141,18 @@ var DynamicRegistry = class {
140
141
  if (existing) {
141
142
  existing.read = read;
142
143
  this.notify();
144
+ this.resourceListeners.forEach((l) => {
145
+ l(uri);
146
+ });
143
147
  }
144
148
  }
149
+ /** Listen for changes to a dynamic resource's content (the in-page `resources/updated`). */
150
+ onResourceUpdated(listener) {
151
+ this.resourceListeners.add(listener);
152
+ return () => {
153
+ this.resourceListeners.delete(listener);
154
+ };
155
+ }
145
156
  getTools() {
146
157
  return [...this.tools.values()];
147
158
  }
@@ -186,25 +197,45 @@ var DynamicRegistry = class {
186
197
  };
187
198
 
188
199
  // libs/react/src/provider/FrontMcpContext.ts
189
- var defaultDynamicRegistry = new DynamicRegistry();
190
- var FrontMcpContext = createContext({
191
- name: "default",
192
- registry: new ComponentRegistry(),
193
- dynamicRegistry: defaultDynamicRegistry,
194
- getDynamicRegistry: () => defaultDynamicRegistry,
195
- connect: async () => {
196
- }
197
- });
200
+ var CONTEXT_KEY = /* @__PURE__ */ Symbol.for("@frontmcp/react/FrontMcpContext");
201
+ function getOrCreateContext() {
202
+ const host = globalThis;
203
+ const existing = host[CONTEXT_KEY];
204
+ if (existing) return existing;
205
+ const defaultDynamicRegistry = new DynamicRegistry();
206
+ const created = createContext({
207
+ name: "default",
208
+ registry: new ComponentRegistry(),
209
+ dynamicRegistry: defaultDynamicRegistry,
210
+ getDynamicRegistry: () => defaultDynamicRegistry,
211
+ connect: async () => {
212
+ }
213
+ });
214
+ host[CONTEXT_KEY] = created;
215
+ return created;
216
+ }
217
+ var FrontMcpContext = getOrCreateContext();
198
218
 
199
219
  // libs/react/src/hooks/useServer.ts
200
- import { useSyncExternalStore, useCallback } from "react";
220
+ import { useCallback, useContext, useSyncExternalStore } from "react";
201
221
 
202
222
  // libs/react/src/registry/ServerRegistry.ts
223
+ function sameListing(a, b) {
224
+ if (a === b) return true;
225
+ if (a.length !== b.length) return false;
226
+ try {
227
+ return JSON.stringify(a) === JSON.stringify(b);
228
+ } catch {
229
+ return false;
230
+ }
231
+ }
203
232
  var ServerRegistry = class {
204
233
  entries = /* @__PURE__ */ new Map();
205
234
  listeners = /* @__PURE__ */ new Set();
235
+ toolListWatches = /* @__PURE__ */ new Map();
206
236
  version = 0;
207
237
  register(name, server) {
238
+ this.stopToolListWatch(name);
208
239
  this.entries.set(name, {
209
240
  server,
210
241
  client: null,
@@ -218,6 +249,7 @@ var ServerRegistry = class {
218
249
  this.notify();
219
250
  }
220
251
  unregister(name) {
252
+ this.stopToolListWatch(name);
221
253
  this.entries.delete(name);
222
254
  this.notify();
223
255
  }
@@ -256,6 +288,7 @@ var ServerRegistry = class {
256
288
  };
257
289
  this.entries.set(name, connected);
258
290
  this.notify();
291
+ this.watchToolList(name, client);
259
292
  return client;
260
293
  } catch (err) {
261
294
  const error = err instanceof Error ? err : new Error(String(err));
@@ -267,6 +300,32 @@ var ServerRegistry = class {
267
300
  async connectAll() {
268
301
  await Promise.all(this.list().map((name) => this.connect(name)));
269
302
  }
303
+ /**
304
+ * Keep `name`'s tool list current: re-list through `client` now, and whenever the server
305
+ * announces `notifications/tools/list_changed` (a dynamic tool registered or removed, say). The
306
+ * first listing catches a change made before the watch began. Only the newest listing is applied,
307
+ * and only while `client` is still the entry's client.
308
+ */
309
+ watchToolList(name, client) {
310
+ this.stopToolListWatch(name);
311
+ if (typeof client.onNotification !== "function") return;
312
+ let latest = 0;
313
+ const relist = () => {
314
+ const listing = ++latest;
315
+ client.listTools().then((tools) => {
316
+ const entry = this.entries.get(name);
317
+ if (listing !== latest || !entry || entry.client !== client) return;
318
+ if (sameListing(entry.tools, tools)) return;
319
+ this.update(name, { tools });
320
+ }).catch(() => {
321
+ });
322
+ };
323
+ const stop = client.onNotification((notification) => {
324
+ if (notification.method === "notifications/tools/list_changed") relist();
325
+ });
326
+ this.toolListWatches.set(name, stop);
327
+ relist();
328
+ }
270
329
  update(name, partial) {
271
330
  const entry = this.entries.get(name);
272
331
  if (entry) {
@@ -275,6 +334,7 @@ var ServerRegistry = class {
275
334
  }
276
335
  }
277
336
  clear() {
337
+ for (const name of [...this.toolListWatches.keys()]) this.stopToolListWatch(name);
278
338
  this.entries.clear();
279
339
  this.notify();
280
340
  }
@@ -287,25 +347,38 @@ var ServerRegistry = class {
287
347
  getVersion() {
288
348
  return this.version;
289
349
  }
350
+ stopToolListWatch(name) {
351
+ const stop = this.toolListWatches.get(name);
352
+ if (!stop) return;
353
+ this.toolListWatches.delete(name);
354
+ stop();
355
+ }
290
356
  notify() {
291
357
  this.version++;
292
358
  this.listeners.forEach((l) => l());
293
359
  }
294
360
  };
295
- var serverRegistry = new ServerRegistry();
361
+ var REGISTRY_KEY = /* @__PURE__ */ Symbol.for("@frontmcp/react/serverRegistry");
362
+ function getOrCreateRegistry() {
363
+ const host = globalThis;
364
+ return host[REGISTRY_KEY] ??= new ServerRegistry();
365
+ }
366
+ var serverRegistry = getOrCreateRegistry();
296
367
 
297
368
  // libs/react/src/hooks/useServer.ts
298
369
  function useServer(name) {
370
+ const ctx = useContext(FrontMcpContext);
371
+ const serverName = name ?? ctx.name;
299
372
  const subscribe = useCallback((cb) => serverRegistry.subscribe(cb), []);
300
373
  const getSnapshot = useCallback(() => {
301
- return serverRegistry.get(name ?? "default");
302
- }, [name]);
374
+ return serverRegistry.get(serverName);
375
+ }, [serverName]);
303
376
  return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
304
377
  }
305
378
 
306
379
  // libs/react/src/hooks/useResolvedServer.ts
307
380
  function useResolvedServer(serverName) {
308
- const ctx = useContext(FrontMcpContext);
381
+ const ctx = useContext2(FrontMcpContext);
309
382
  const resolvedName = serverName ?? ctx.name;
310
383
  const entry = useServer(resolvedName);
311
384
  return { entry, name: resolvedName, registry: ctx.registry, connect: ctx.connect };
package/esm/api/index.mjs CHANGED
@@ -58,22 +58,23 @@ var DynamicRegistry = class {
58
58
  toolRefCounts = /* @__PURE__ */ new Map();
59
59
  resourceRefCounts = /* @__PURE__ */ new Map();
60
60
  listeners = /* @__PURE__ */ new Set();
61
+ resourceListeners = /* @__PURE__ */ new Set();
61
62
  version = 0;
62
63
  /**
63
64
  * Register a dynamic tool. Returns an unregister function
64
65
  * suitable for useEffect cleanup.
65
66
  *
66
67
  * Multiple registrations of the same name are ref-counted:
67
- * subsequent registrations update the definition but the tool
68
- * is only removed when every registrant has unregistered.
68
+ * subsequent registrations replace the definition (and notify, so
69
+ * the server registration follows the new description, schema or
70
+ * availability) but the tool is only removed when every registrant
71
+ * has unregistered.
69
72
  */
70
73
  registerTool(def) {
71
74
  const existing = this.toolRefCounts.get(def.name) ?? 0;
72
75
  this.toolRefCounts.set(def.name, existing + 1);
73
76
  this.tools.set(def.name, def);
74
- if (existing === 0) {
75
- this.notify();
76
- }
77
+ this.notify();
77
78
  let called = false;
78
79
  return () => {
79
80
  if (called) return;
@@ -136,8 +137,18 @@ var DynamicRegistry = class {
136
137
  if (existing) {
137
138
  existing.read = read;
138
139
  this.notify();
140
+ this.resourceListeners.forEach((l) => {
141
+ l(uri);
142
+ });
139
143
  }
140
144
  }
145
+ /** Listen for changes to a dynamic resource's content (the in-page `resources/updated`). */
146
+ onResourceUpdated(listener) {
147
+ this.resourceListeners.add(listener);
148
+ return () => {
149
+ this.resourceListeners.delete(listener);
150
+ };
151
+ }
141
152
  getTools() {
142
153
  return [...this.tools.values()];
143
154
  }
@@ -182,15 +193,24 @@ var DynamicRegistry = class {
182
193
  };
183
194
 
184
195
  // libs/react/src/provider/FrontMcpContext.ts
185
- var defaultDynamicRegistry = new DynamicRegistry();
186
- var FrontMcpContext = createContext({
187
- name: "default",
188
- registry: new ComponentRegistry(),
189
- dynamicRegistry: defaultDynamicRegistry,
190
- getDynamicRegistry: () => defaultDynamicRegistry,
191
- connect: async () => {
192
- }
193
- });
196
+ var CONTEXT_KEY = /* @__PURE__ */ Symbol.for("@frontmcp/react/FrontMcpContext");
197
+ function getOrCreateContext() {
198
+ const host = globalThis;
199
+ const existing = host[CONTEXT_KEY];
200
+ if (existing) return existing;
201
+ const defaultDynamicRegistry = new DynamicRegistry();
202
+ const created = createContext({
203
+ name: "default",
204
+ registry: new ComponentRegistry(),
205
+ dynamicRegistry: defaultDynamicRegistry,
206
+ getDynamicRegistry: () => defaultDynamicRegistry,
207
+ connect: async () => {
208
+ }
209
+ });
210
+ host[CONTEXT_KEY] = created;
211
+ return created;
212
+ }
213
+ var FrontMcpContext = getOrCreateContext();
194
214
 
195
215
  // libs/react/src/api/createFetchClient.ts
196
216
  function createFetchClient(fetchFn) {
@@ -232,29 +252,91 @@ function interpolatePath(path, params) {
232
252
  return value != null ? encodeURIComponent(String(value)) : `{${key}}`;
233
253
  });
234
254
  }
255
+ function paramText(value) {
256
+ return typeof value === "object" && value !== null ? JSON.stringify(value) : String(value);
257
+ }
258
+ function isRecord(value) {
259
+ return typeof value === "object" && value !== null && !Array.isArray(value);
260
+ }
261
+ var QUERY_DELIMITERS = { spaceDelimited: "%20", pipeDelimited: "%7C" };
262
+ function serializedItems(value, explode, encode) {
263
+ if (Array.isArray(value)) return value.map((item) => encode(paramText(item)));
264
+ return Object.entries(value).flatMap(
265
+ ([key, item]) => explode ? [`${encode(key)}=${encode(paramText(item))}`] : [encode(key), encode(paramText(item))]
266
+ );
267
+ }
268
+ function queryPairs(param, value) {
269
+ const style = param.style ?? "form";
270
+ const explode = param.explode ?? style === "form";
271
+ const name = encodeURIComponent(param.name);
272
+ if (style === "deepObject" && isRecord(value)) {
273
+ return Object.entries(value).map(
274
+ ([key, item]) => `${encodeURIComponent(`${param.name}[${key}]`)}=${encodeURIComponent(paramText(item))}`
275
+ );
276
+ }
277
+ if (!Array.isArray(value) && !isRecord(value)) return [`${name}=${encodeURIComponent(paramText(value))}`];
278
+ const items = serializedItems(value, explode, encodeURIComponent);
279
+ if (!explode) return [`${name}=${items.join(QUERY_DELIMITERS[style] ?? ",")}`];
280
+ return Array.isArray(value) ? items.map((item) => `${name}=${item}`) : items;
281
+ }
282
+ function buildRequestUrl(baseUrl, op, args) {
283
+ const pairs = [];
284
+ for (const param of op.parameters ?? []) {
285
+ if (param.in !== "query") continue;
286
+ const value = args[param.name];
287
+ if (value === void 0 || value === null) continue;
288
+ pairs.push(...queryPairs(param, value));
289
+ }
290
+ const url = baseUrl + interpolatePath(op.path, args);
291
+ return pairs.length > 0 ? `${url}${url.includes("?") ? "&" : "?"}${pairs.join("&")}` : url;
292
+ }
293
+ function headerText(param, value) {
294
+ if (!Array.isArray(value) && !isRecord(value)) return paramText(value);
295
+ return serializedItems(value, param.explode ?? false, (text) => text).join(",");
296
+ }
297
+ function headerParams(op, args) {
298
+ const headers = {};
299
+ for (const param of op.parameters ?? []) {
300
+ if (param.in !== "header") continue;
301
+ const value = args[param.name];
302
+ if (value !== void 0 && value !== null) headers[param.name] = headerText(param, value);
303
+ }
304
+ return headers;
305
+ }
306
+ function registrationKey(operations) {
307
+ return JSON.stringify(
308
+ operations.map((op) => [op.operationId, op.description, op.method, op.path, op.inputSchema, op.parameters ?? null])
309
+ );
310
+ }
235
311
  function useApiClient(options) {
236
312
  const { baseUrl, operations, headers, prefix = "api", client, fetch: customFetch } = options;
237
313
  const { getDynamicRegistry } = useContext(FrontMcpContext);
238
314
  const dynamicRegistry = getDynamicRegistry(options.server);
315
+ const baseUrlRef = useRef(baseUrl);
239
316
  const headersRef = useRef(headers);
240
- headersRef.current = headers;
317
+ const operationsRef = useRef(operations);
241
318
  const clientRef = useRef(client ?? createFetchClient(customFetch));
242
- clientRef.current = client ?? createFetchClient(customFetch);
243
319
  useEffect(() => {
244
- const cleanups = [];
245
- for (const op of operations) {
246
- const toolName = `${prefix}_${op.operationId}`;
320
+ baseUrlRef.current = baseUrl;
321
+ headersRef.current = headers;
322
+ operationsRef.current = operations;
323
+ clientRef.current = client ?? createFetchClient(customFetch);
324
+ }, [baseUrl, headers, operations, client, customFetch]);
325
+ const key = registrationKey(operations);
326
+ useEffect(() => {
327
+ const cleanups = operationsRef.current.map((registered) => {
247
328
  const execute = async (args) => {
329
+ const op = operationsRef.current.find((o) => o.operationId === registered.operationId) ?? registered;
248
330
  const resolvedHeaders = {
249
331
  "Content-Type": "application/json",
250
- ...typeof headersRef.current === "function" ? headersRef.current() : headersRef.current ?? {}
332
+ ...typeof headersRef.current === "function" ? headersRef.current() : headersRef.current ?? {},
333
+ ...headerParams(op, args)
251
334
  };
252
- const url = baseUrl + interpolatePath(op.path, args);
253
335
  const body = args["body"];
254
336
  const method = op.method;
255
337
  const requestConfig = {
256
338
  method,
257
- url,
339
+ url: buildRequestUrl(baseUrlRef.current, op, args),
258
340
  headers: resolvedHeaders
259
341
  };
260
342
  if (body !== void 0 && method !== "GET" && method !== "HEAD") {
@@ -275,25 +357,37 @@ function useApiClient(options) {
275
357
  isError: response.status >= 400
276
358
  };
277
359
  };
278
- cleanups.push(
279
- dynamicRegistry.registerTool({
280
- name: toolName,
281
- description: op.description,
282
- inputSchema: op.inputSchema,
283
- execute
284
- })
285
- );
286
- }
360
+ return dynamicRegistry.registerTool({
361
+ name: `${prefix}_${registered.operationId}`,
362
+ description: registered.description,
363
+ inputSchema: registered.inputSchema,
364
+ execute
365
+ });
366
+ });
287
367
  return () => {
288
368
  cleanups.forEach((fn) => {
289
369
  fn();
290
370
  });
291
371
  };
292
- }, [dynamicRegistry, baseUrl, operations, prefix, client, customFetch]);
372
+ }, [dynamicRegistry, prefix, key]);
293
373
  }
294
374
 
295
375
  // libs/react/src/api/parseOpenApiSpec.ts
296
376
  var HTTP_METHODS = ["get", "post", "put", "delete", "patch", "options", "head"];
377
+ var PARAMETER_LOCATIONS = ["path", "query", "header", "cookie"];
378
+ var PARAMETER_STYLES = [
379
+ "form",
380
+ "spaceDelimited",
381
+ "pipeDelimited",
382
+ "deepObject",
383
+ "simple"
384
+ ];
385
+ function toApiParameter(param) {
386
+ const parameter = { name: param.name, in: param.in };
387
+ if (PARAMETER_STYLES.includes(param.style)) parameter.style = param.style;
388
+ if (typeof param.explode === "boolean") parameter.explode = param.explode;
389
+ return parameter;
390
+ }
297
391
  function parseOpenApiSpec(spec) {
298
392
  const paths = spec["paths"];
299
393
  if (!paths) return [];
@@ -333,6 +427,7 @@ function parseOpenApiSpec(spec) {
333
427
  }
334
428
  }
335
429
  const propertyLocations = /* @__PURE__ */ new Map();
430
+ const parameters = [];
336
431
  for (const param of paramMap.values()) {
337
432
  if (param.name === "__proto__" || param.name === "constructor" || param.name === "prototype") continue;
338
433
  const existingIn = propertyLocations.get(param.name);
@@ -347,6 +442,7 @@ function parseOpenApiSpec(spec) {
347
442
  description: param.description
348
443
  };
349
444
  if (param.required) required.push(param.name);
445
+ if (PARAMETER_LOCATIONS.includes(param.in)) parameters.push(toApiParameter(param));
350
446
  }
351
447
  const requestBody = operation["requestBody"];
352
448
  if (requestBody) {
@@ -367,7 +463,14 @@ function parseOpenApiSpec(spec) {
367
463
  if (required.length > 0) {
368
464
  inputSchema["required"] = required;
369
465
  }
370
- operations.push({ operationId, description, method: method.toUpperCase(), path, inputSchema });
466
+ operations.push({
467
+ operationId,
468
+ description,
469
+ method: method.toUpperCase(),
470
+ path,
471
+ inputSchema,
472
+ ...parameters.length > 0 ? { parameters } : {}
473
+ });
371
474
  }
372
475
  }
373
476
  return operations;