socialcrawl-mcp 2.0.0 → 2.0.2

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 (59) hide show
  1. package/README.md +94 -112
  2. package/dist/client.d.ts +2 -0
  3. package/dist/client.js +4 -0
  4. package/dist/constants.d.ts +10 -1
  5. package/dist/constants.js +10 -1
  6. package/dist/cost-guard.d.ts +8 -1
  7. package/dist/cost-guard.js +21 -9
  8. package/dist/data/docs-handwritten.js +4 -3
  9. package/dist/data/docs.js +1 -1
  10. package/dist/data/endpoints.js +65 -33
  11. package/dist/data/examples.js +1 -1
  12. package/dist/data/guide.d.ts +1 -1
  13. package/dist/data/guide.js +1 -1
  14. package/dist/data/outputs.js +218 -217
  15. package/dist/data/platforms.js +1 -1
  16. package/dist/data/recipes.js +1 -1
  17. package/dist/data/registry-meta.d.ts +4 -4
  18. package/dist/data/registry-meta.js +4 -4
  19. package/dist/endpoint-resolve.d.ts +10 -0
  20. package/dist/endpoint-resolve.js +34 -0
  21. package/dist/format/shape.d.ts +6 -0
  22. package/dist/format/shape.js +64 -0
  23. package/dist/freshness.d.ts +27 -4
  24. package/dist/freshness.js +42 -19
  25. package/dist/oauth/jwt-verifier.js +7 -0
  26. package/dist/oauth/resource-server.d.ts +3 -1
  27. package/dist/oauth/resource-server.js +12 -2
  28. package/dist/oauth/scopes.d.ts +13 -0
  29. package/dist/oauth/scopes.js +33 -0
  30. package/dist/result.d.ts +2 -0
  31. package/dist/result.js +8 -0
  32. package/dist/schemas/normalize.d.ts +27 -0
  33. package/dist/schemas/normalize.js +189 -0
  34. package/dist/schemas/outputs.d.ts +51 -31
  35. package/dist/schemas/outputs.js +10 -4
  36. package/dist/schemas/tools.d.ts +43 -8
  37. package/dist/schemas/tools.js +20 -7
  38. package/dist/server.js +17 -12
  39. package/dist/tools/cohorts.d.ts +3 -1
  40. package/dist/tools/cohorts.js +11 -10
  41. package/dist/tools/collect.d.ts +7 -3
  42. package/dist/tools/collect.js +110 -9
  43. package/dist/tools/discover.js +22 -27
  44. package/dist/tools/endpoint.js +9 -5
  45. package/dist/tools/estimate.js +53 -9
  46. package/dist/tools/find.d.ts +4 -0
  47. package/dist/tools/find.js +276 -9
  48. package/dist/tools/manage.d.ts +4 -0
  49. package/dist/tools/manage.js +106 -4
  50. package/dist/tools/monitors.d.ts +8 -1
  51. package/dist/tools/monitors.js +17 -12
  52. package/dist/tools/pricing.d.ts +1 -5
  53. package/dist/tools/pricing.js +17 -0
  54. package/dist/tools/request.d.ts +2 -11
  55. package/dist/tools/request.js +123 -74
  56. package/dist/tools/web.d.ts +3 -1
  57. package/dist/tools/web.js +4 -3
  58. package/dist/types.d.ts +9 -4
  59. package/package.json +2 -2
@@ -1,5 +1,5 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { apiRequest } from "../client.js";
2
+ import { apiRequest, withDryRun } from "../client.js";
3
3
  /**
4
4
  * The ten platforms a cohort identity may name. Anything else is rejected at
5
5
  * upload with 400 COHORT_IDENTITY_PLATFORM_UNSUPPORTED, so checking locally
@@ -121,7 +121,8 @@ function unsupportedPlatforms(platforms) {
121
121
  const allowed = new Set(COHORT_IDENTITY_PLATFORMS);
122
122
  return [...new Set(platforms.filter((p) => !allowed.has(p)))];
123
123
  }
124
- export async function cohorts(ctx, input) {
124
+ export async function cohorts(ctx, input, opts = {}) {
125
+ const send = (o) => apiRequest(ctx, withDryRun(o, opts.dryRun));
125
126
  const { action } = input;
126
127
  const needsCohort = new Set(["get", "delete", "add_members", "query"]);
127
128
  const needsQuery = new Set(["query_status", "query_results", "query_cancel"]);
@@ -198,7 +199,7 @@ export async function cohorts(ctx, input) {
198
199
  }
199
200
  body.retention_days = input.retention_days;
200
201
  }
201
- response = await apiRequest(ctx, {
202
+ response = await send({
202
203
  method: "POST",
203
204
  path: "/v1/cohorts",
204
205
  body,
@@ -209,7 +210,7 @@ export async function cohorts(ctx, input) {
209
210
  break;
210
211
  }
211
212
  case "get": {
212
- response = await apiRequest(ctx, {
213
+ response = await send({
213
214
  method: "GET",
214
215
  path: `/v1/cohorts/${cohortId}`,
215
216
  errorPlatform: "cohorts",
@@ -218,7 +219,7 @@ export async function cohorts(ctx, input) {
218
219
  break;
219
220
  }
220
221
  case "delete": {
221
- response = await apiRequest(ctx, {
222
+ response = await send({
222
223
  method: "DELETE",
223
224
  path: `/v1/cohorts/${cohortId}`,
224
225
  errorPlatform: "cohorts",
@@ -245,7 +246,7 @@ export async function cohorts(ctx, input) {
245
246
  if (bad.length > 0) {
246
247
  return `Error: Unsupported cohort platform(s): ${bad.join(", ")}. Cohort identities must be one of ${COHORT_IDENTITY_PLATFORMS.join(", ")}.`;
247
248
  }
248
- response = await apiRequest(ctx, {
249
+ response = await send({
249
250
  method: "PUT",
250
251
  path: `/v1/cohorts/${cohortId}/members`,
251
252
  body: { members },
@@ -308,7 +309,7 @@ export async function cohorts(ctx, input) {
308
309
  body.date_to = input.date_to;
309
310
  if (input.platforms && input.platforms.length > 0)
310
311
  body.platforms = input.platforms;
311
- response = await apiRequest(ctx, {
312
+ response = await send({
312
313
  method: "POST",
313
314
  path: `/v1/cohorts/${cohortId}/queries`,
314
315
  body,
@@ -321,7 +322,7 @@ export async function cohorts(ctx, input) {
321
322
  break;
322
323
  }
323
324
  case "query_status": {
324
- response = await apiRequest(ctx, {
325
+ response = await send({
325
326
  method: "GET",
326
327
  path: `/v1/cohort-queries/${queryId}`,
327
328
  errorPlatform: "cohorts",
@@ -338,7 +339,7 @@ export async function cohorts(ctx, input) {
338
339
  limit: input.limit?.toString(),
339
340
  cursor: input.cursor,
340
341
  });
341
- response = await apiRequest(ctx, {
342
+ response = await send({
342
343
  method: "GET",
343
344
  path: `/v1/cohort-queries/${queryId}/results`,
344
345
  query,
@@ -348,7 +349,7 @@ export async function cohorts(ctx, input) {
348
349
  break;
349
350
  }
350
351
  case "query_cancel": {
351
- response = await apiRequest(ctx, {
352
+ response = await send({
352
353
  method: "DELETE",
353
354
  path: `/v1/cohort-queries/${queryId}`,
354
355
  errorPlatform: "cohorts",
@@ -2,13 +2,17 @@ import type { ApiContext } from "../context.js";
2
2
  import type { ToolOutput } from "../result.js";
3
3
  export interface CollectParams {
4
4
  /** `platform/resource`, e.g. `tiktok/post/comments`. */
5
- id: string;
5
+ id?: string;
6
6
  params?: Record<string, string | number | boolean | Array<string | number | boolean>>;
7
- items: number;
7
+ items?: number;
8
8
  max_credits?: number;
9
9
  format?: "jsonl" | "json" | "csv";
10
10
  fields?: string;
11
11
  confirm?: boolean;
12
+ /** Read a stored result (a walk's, or a request's full body) instead of walking. */
13
+ result_id?: string;
14
+ offset?: number;
15
+ limit?: number;
12
16
  }
13
17
  /**
14
18
  * Walk a paged endpoint (cursor) until `items` unique rows, the last page, or
@@ -17,4 +21,4 @@ export interface CollectParams {
17
21
  * could spend past the confirmation threshold; stops cleanly on a 402. The
18
22
  * rows are stored (JSONL by default) behind a resource link.
19
23
  */
20
- export declare function collectStructured(ctx: ApiContext, input: CollectParams): Promise<ToolOutput>;
24
+ export declare function collectStructured(ctx: ApiContext, raw: CollectParams): Promise<ToolOutput>;
@@ -2,8 +2,9 @@ import { randomUUID } from "node:crypto";
2
2
  import { findPlatform } from "../data/platforms.js";
3
3
  import { checkGuard, quoteCall } from "../cost-guard.js";
4
4
  import { flattenRows, toCsv } from "../format/csv.js";
5
- import { errorFromText, structureEnvelope } from "../result.js";
6
- import { resultsStore, resultUri, scopeOf } from "../results-store.js";
5
+ import { errorFromText, shortCursor, structureEnvelope } from "../result.js";
6
+ import { INLINE_MAX_BYTES, INLINE_MAX_ROWS } from "../constants.js";
7
+ import { RESULT_URI_PREFIX, resultsStore, resultUri, scopeOf } from "../results-store.js";
7
8
  import { sessionTotal } from "../session-spend.js";
8
9
  import { requestPage, resolveEndpoint, stringifyParams } from "./request.js";
9
10
  /** Hard stop on pages per call, so a cursor that never ends cannot loop. */
@@ -13,6 +14,79 @@ const SAMPLE_ROWS = 3;
13
14
  const DEFAULT_PAGE_SIZE = 20;
14
15
  const MIME = { jsonl: "application/x-ndjson", json: "application/json", csv: "text/csv" };
15
16
  const fail = (text) => ({ text, structured: errorFromText(text) });
17
+ /** Rows a result_id read returns when no limit is given. */
18
+ const READ_DEFAULT_LIMIT = 200;
19
+ const READ_MAX_LIMIT = 1000;
20
+ /** The rows a walk collected, as JSON, kept beside the formatted body for result_id reads. */
21
+ const rowsKey = (id) => `rows:${id}`;
22
+ /** Rows in `format`, for the text. */
23
+ function renderRows(rows, format) {
24
+ if (format === "csv")
25
+ return `\`\`\`csv\n${toCsv(flattenRows(rows))}\n\`\`\``;
26
+ if (format === "jsonl")
27
+ return `\`\`\`jsonl\n${rows.map((r) => JSON.stringify(r)).join("\n")}\n\`\`\``;
28
+ return `\`\`\`json\n${JSON.stringify(rows)}\n\`\`\``;
29
+ }
30
+ /** The rows of a stored body: a JSON array, an API envelope, JSONL, or (last resort) one value. */
31
+ function rowsOf(body) {
32
+ try {
33
+ const parsed = JSON.parse(body);
34
+ if (Array.isArray(parsed))
35
+ return parsed;
36
+ const s = structureEnvelope(parsed);
37
+ if (Array.isArray(s.rows))
38
+ return s.rows;
39
+ return s.data !== undefined ? [s.data] : [parsed];
40
+ }
41
+ catch {
42
+ const lines = body.split("\n").filter((l) => l.trim() !== "");
43
+ try {
44
+ return lines.map((l) => JSON.parse(l));
45
+ }
46
+ catch {
47
+ return undefined;
48
+ }
49
+ }
50
+ }
51
+ /** `socialcrawl_collect` with `result_id`: read a stored result back, a slice at a time. Free. */
52
+ function readStored(ctx, input) {
53
+ const id = String(input.result_id).trim().replace(RESULT_URI_PREFIX, "");
54
+ const scope = scopeOf(ctx.apiKey);
55
+ const kept = resultsStore.get(scope, rowsKey(id));
56
+ const body = kept ?? resultsStore.get(scope, id);
57
+ if (body === undefined) {
58
+ return fail(`Error: No stored result for "${id}". Stored results expire after 30 minutes; repeat the request or walk (a cached repeat is free).`);
59
+ }
60
+ const rows = rowsOf(body);
61
+ if (!rows) {
62
+ // Not rows (e.g. a CSV body from an older walk): hand back the text as stored.
63
+ return { text: body, structured: { ok: true, result_id: id } };
64
+ }
65
+ const offset = Math.max(0, Math.floor(input.offset ?? 0));
66
+ const limit = Math.min(READ_MAX_LIMIT, Math.max(1, Math.floor(input.limit ?? READ_DEFAULT_LIMIT)));
67
+ const slice = rows.slice(offset, offset + limit);
68
+ const format = input.format ?? "json";
69
+ const end = offset + slice.length;
70
+ const structured = {
71
+ ok: true,
72
+ result_id: id,
73
+ format,
74
+ offset,
75
+ total: rows.length,
76
+ resource: resultUri(id),
77
+ };
78
+ // A CSV read keeps the table once, in the text.
79
+ if (format !== "csv")
80
+ structured.rows = slice;
81
+ const more = end < rows.length ? ` Next: offset ${end}.` : "";
82
+ const text = [
83
+ `## SocialCrawl Stored Result`,
84
+ `**Result:** ${id} · rows ${slice.length === 0 ? "none" : `${offset + 1}-${end}`} of ${rows.length} (${format}).${more}`,
85
+ "",
86
+ renderRows(slice, format),
87
+ ].join("\n");
88
+ return { text, structured };
89
+ }
16
90
  /** Stable identity for dedupe: the row's `id`, else its `url`, else its whole JSON. */
17
91
  function rowKey(row) {
18
92
  if (typeof row === "object" && row !== null) {
@@ -31,7 +105,16 @@ function rowKey(row) {
31
105
  * could spend past the confirmation threshold; stops cleanly on a 402. The
32
106
  * rows are stored (JSONL by default) behind a resource link.
33
107
  */
34
- export async function collectStructured(ctx, input) {
108
+ export async function collectStructured(ctx, raw) {
109
+ if (raw.result_id !== undefined)
110
+ return readStored(ctx, raw);
111
+ if (!raw.id) {
112
+ return fail('Error: Missing required parameter(s): `id` (e.g. "tiktok/post/comments"), or `result_id` to read a stored result. No credits were charged.');
113
+ }
114
+ if (raw.items === undefined) {
115
+ return fail("Error: Missing required parameter(s): `items` (unique rows to collect). No credits were charged.");
116
+ }
117
+ const input = { ...raw, id: raw.id, items: raw.items };
35
118
  const slash = input.id.indexOf("/");
36
119
  const platformSlug = slash > 0 ? input.id.slice(0, slash) : "";
37
120
  const resource = slash > 0 ? input.id.slice(slash + 1) : "";
@@ -171,13 +254,24 @@ export async function collectStructured(ctx, input) {
171
254
  ? JSON.stringify(kept)
172
255
  : toCsv(flattenRows(kept));
173
256
  let uri;
257
+ let resultId;
174
258
  if (kept.length > 0) {
175
259
  const id = randomUUID();
176
- if (resultsStore.put(scopeOf(ctx.apiKey), id, body))
260
+ if (resultsStore.put(scopeOf(ctx.apiKey), id, body)) {
177
261
  uri = resultUri(id);
262
+ resultId = id;
263
+ // The rows as JSON too, so a result_id read can slice and re-format them.
264
+ if (format !== "json")
265
+ resultsStore.put(scopeOf(ctx.apiKey), rowsKey(id), JSON.stringify(kept));
266
+ }
178
267
  else
179
268
  warnings.push(`collected rows (${Buffer.byteLength(body).toLocaleString()} bytes) are too large to store; collect fewer items.`);
180
269
  }
270
+ // Whole in the text when the rows, in the format asked for, fit; whole in structuredContent when their JSON does.
271
+ const fewRows = kept.length > 0 && kept.length <= INLINE_MAX_ROWS;
272
+ const rendered = fewRows ? renderRows(kept, format) : "";
273
+ const inline = fewRows && Buffer.byteLength(rendered) <= INLINE_MAX_BYTES;
274
+ const rowsInline = fewRows && Buffer.byteLength(JSON.stringify(kept)) <= INLINE_MAX_BYTES;
181
275
  const total = sessionTotal(ctx.apiKey);
182
276
  const structured = {
183
277
  ok: true,
@@ -194,23 +288,30 @@ export async function collectStructured(ctx, input) {
194
288
  session_total: total,
195
289
  },
196
290
  paging: { has_more: hasMore && cursor !== null, next_cursor: hasMore ? cursor : null },
197
- sample: kept.slice(0, SAMPLE_ROWS),
291
+ ...(rowsInline ? { rows: kept } : { sample: kept.slice(0, SAMPLE_ROWS) }),
198
292
  };
199
293
  if (uri)
200
294
  structured.resource = uri;
295
+ if (resultId)
296
+ structured.result_id = resultId;
201
297
  if (warnings.length > 0)
202
298
  structured.warnings = warnings;
299
+ const where = cursor && cursor.length > 64 ? " (full value: structuredContent paging.next_cursor)" : "";
203
300
  const resume = hasMore && cursor && reason !== "items" && reason !== "exhausted"
204
- ? ` Resume with params.cursor="${cursor}".`
301
+ ? ` Resume with params.cursor="${shortCursor(cursor)}"${where}.`
205
302
  : hasMore && cursor && reason === "items"
206
- ? ` More rows remain; next cursor "${cursor}".`
303
+ ? ` More rows remain; next cursor "${shortCursor(cursor)}"${where}.`
207
304
  : "";
208
305
  const text = [
209
306
  `## SocialCrawl Collect`,
210
307
  `**Endpoint:** \`GET /v1/${endpointName}\` walked ${pages} page${pages === 1 ? "" : "s"} (${quote.source} quote: up to ${quote.hold}cr per page)`,
211
308
  `**Result:** ok ${endpointName} · ${kept.length} of ${input.items} items (${duplicates} duplicate${duplicates === 1 ? "" : "s"} dropped) · credits used ${used}${remaining !== undefined ? `, ${remaining} remaining` : ""} · session total ${total} · stopped: ${reason}.${resume}`,
212
- uri ? `All ${kept.length} rows (${format}) stored as resource ${uri}` : "",
213
- kept.length > 0 ? `\n\`\`\`json\n${JSON.stringify(kept.slice(0, SAMPLE_ROWS))}\n\`\`\`` : "",
309
+ resultId
310
+ ? inline
311
+ ? `All ${kept.length} rows below (${format}). To re-read or re-format them, read it in this session with result_id ${resultId} (socialcrawl_collect).`
312
+ : `All ${kept.length} rows (${format}) are stored; first ${Math.min(SAMPLE_ROWS, kept.length)} below. Read them in this session with result_id ${resultId}: socialcrawl_collect { result_id, offset, limit, format }.`
313
+ : "",
314
+ kept.length > 0 ? `\n${inline ? rendered : `\`\`\`json\n${JSON.stringify(kept.slice(0, SAMPLE_ROWS))}\n\`\`\``}` : "",
214
315
  ...warnings.map((w) => `Note: ${w}`),
215
316
  ]
216
317
  .filter((l) => l !== "")
@@ -2,6 +2,7 @@ import { apiRequest, makeRequest } from "../client.js";
2
2
  import { ENDPOINTS, findEndpoint, getEndpointsByPlatform } from "../data/endpoints.js";
3
3
  import { PLATFORMS, findPlatform } from "../data/platforms.js";
4
4
  import { REGISTRY_FINGERPRINT, REGISTRY_STATS } from "../data/registry-meta.js";
5
+ import { checkFreshness } from "../freshness.js";
5
6
  import { capabilityIndex } from "../judgments.js";
6
7
  import { SERVER_VERSION } from "../constants.js";
7
8
  import { page } from "../paginate.js";
@@ -507,37 +508,40 @@ function renderPlan(data, query) {
507
508
  return lines.join("\n");
508
509
  }
509
510
  // ── freshness ──────────────────────────────────────────────────────────
510
- function renderFreshness(live) {
511
- if (!live) {
511
+ function renderFreshness(report) {
512
+ const bundledFp = REGISTRY_FINGERPRINT.slice(0, 12);
513
+ if (report.state === "unknown" || !report.live) {
512
514
  return [
513
515
  "# Catalogue freshness — could not reach the live registry",
514
516
  "",
515
- "The check calls `GET /v1/utility/endpoints` (0 credits) and compares its live registry stats against this server's bundled catalogue. It needs a configured API key and network access.",
517
+ "The check calls `GET /v1/utility/endpoints` (0 credits) and compares the live registry fingerprint (or, failing that, its platform and endpoint counts) with this server's bundled catalogue. It needs a configured API key and network access.",
516
518
  "",
517
- `Bundled catalogue: **${REGISTRY_STATS.totalPlatforms} platforms, ${REGISTRY_STATS.totalEndpoints} endpoints** (socialcrawl-mcp v${SERVER_VERSION}, registry fingerprint \`${REGISTRY_FINGERPRINT.slice(0, 12)}\`).`,
519
+ `Bundled catalogue: **${REGISTRY_STATS.totalPlatforms} platforms, ${REGISTRY_STATS.totalEndpoints} endpoints** (socialcrawl-mcp v${SERVER_VERSION}, registry fingerprint \`${bundledFp}\`).`,
518
520
  ].join("\n");
519
521
  }
520
- const samePlatforms = live.platforms === REGISTRY_STATS.totalPlatforms;
521
- const sameEndpoints = live.endpoints === REGISTRY_STATS.totalEndpoints;
522
- const current = samePlatforms && sameEndpoints;
522
+ const live = report.live;
523
+ const current = report.state === "fresh";
524
+ const liveFp = live.fingerprint ? `\`${live.fingerprint.slice(0, 12)}\`` : "not published";
523
525
  const lines = [
524
526
  `# Catalogue freshness — ${current ? "up to date" : "OUT OF DATE"}`,
525
527
  "",
526
- "| | Platforms | Endpoints |",
527
- "|---|-----------|-----------|",
528
- `| Live API | ${live.platforms ?? "?"} | ${live.endpoints ?? "?"} |`,
529
- `| This server (v${SERVER_VERSION}) | ${REGISTRY_STATS.totalPlatforms} | ${REGISTRY_STATS.totalEndpoints} |`,
528
+ "| | Platforms | Endpoints | Fingerprint |",
529
+ "|---|-----------|-----------|-------------|",
530
+ `| Live API | ${live.platforms ?? "?"} | ${live.endpoints ?? "?"} | ${liveFp} |`,
531
+ `| This server (v${SERVER_VERSION}) | ${REGISTRY_STATS.totalPlatforms} | ${REGISTRY_STATS.totalEndpoints} | \`${bundledFp}\` |`,
530
532
  "",
531
- `Bundled registry fingerprint: \`${REGISTRY_FINGERPRINT.slice(0, 12)}\` (a hash of every endpoint's method, path and parameter names). Equal counts with a different backend fingerprint mean a parameter changed; \`action: "endpoint"\` always reads the live contract.`,
533
+ `Compared by ${report.basis === "fingerprint" ? "registry fingerprint (a hash of every endpoint's method, path and parameter names)" : "platform and endpoint counts (the live API publishes no fingerprint)"}. \`socialcrawl_endpoint\` with a key always reads the live contract.`,
532
534
  "",
533
535
  ];
534
536
  if (current) {
535
537
  lines.push("This server's bundled catalogue matches the live registry. Discovery, pricing, and validation answered from bundled data are current.");
536
538
  }
537
539
  else {
538
- const dPlatforms = (live.platforms ?? 0) - REGISTRY_STATS.totalPlatforms;
539
- const dEndpoints = (live.endpoints ?? 0) - REGISTRY_STATS.totalEndpoints;
540
- lines.push(`The live API has **${dEndpoints >= 0 ? "+" : ""}${dEndpoints} endpoints** and **${dPlatforms >= 0 ? "+" : ""}${dPlatforms} platforms** relative to this server's bundled catalogue.`, "", "**What this means:** `socialcrawl_request` still calls the live API and works for any endpoint — but this server's *discovery* surfaces (`list_platforms`, `list_endpoints`, `pricing`, `get_docs`) and its local parameter validation are answering from a snapshot, so a newer endpoint will look unknown.", "", "**What to do:**", "- Upgrade the package: `npx -y socialcrawl-mcp@latest` (or bump the pinned version in your MCP client config).", "- Until then, use `socialcrawl_endpoint` with a key — it reads the live registry and is always correct.");
540
+ const dPlatforms = (live.platforms ?? REGISTRY_STATS.totalPlatforms) - REGISTRY_STATS.totalPlatforms;
541
+ const dEndpoints = (live.endpoints ?? REGISTRY_STATS.totalEndpoints) - REGISTRY_STATS.totalEndpoints;
542
+ lines.push(dPlatforms === 0 && dEndpoints === 0
543
+ ? "The counts match but the fingerprints differ: an endpoint's parameters changed since this server was built."
544
+ : `The live API has **${dEndpoints >= 0 ? "+" : ""}${dEndpoints} endpoints** and **${dPlatforms >= 0 ? "+" : ""}${dPlatforms} platforms** relative to this server's bundled catalogue.`, "", "**What this means:** `socialcrawl_request` still calls the live API and works for any endpoint — but this server's bundled answers (`socialcrawl_find` offline, `socialcrawl_estimate` without a key, local parameter validation) come from a snapshot, so a newer endpoint or parameter can look unknown.", "", "**What to do:**", "- Upgrade the package: `npx -y socialcrawl-mcp@latest` (or bump the pinned version in your MCP client config).", "- Until then, use `socialcrawl_endpoint` with a key — it reads the live registry and is always correct.");
541
545
  }
542
546
  return lines.join("\n");
543
547
  }
@@ -687,18 +691,9 @@ export async function discover(ctx, params) {
687
691
  }
688
692
  case "freshness": {
689
693
  if (!canGoLive)
690
- return renderFreshness(null);
691
- // Ask for a filter that matches nothing: the `stats` block is always the
692
- // whole-registry totals regardless of filter, so this returns the live
693
- // counts in a few hundred bytes instead of all 381 catalogue rows.
694
- const response = await makeRequest(ctx, {
695
- platform: "utility",
696
- resource: "endpoints",
697
- params: { search: "freshness-probe" },
698
- });
699
- const data = envelopeData(response);
700
- const stats = data?.stats;
701
- return renderFreshness(stats ?? null);
694
+ return renderFreshness({ state: "unknown" });
695
+ // The same check as the stale note on tool results (freshness.ts).
696
+ return renderFreshness(await checkFreshness(ctx));
702
697
  }
703
698
  case "status": {
704
699
  // `GET /v1/status` is a public meta route (`security: []`), not a
@@ -150,7 +150,7 @@ function cleanNext(raw) {
150
150
  export function contractFor(e) {
151
151
  const out = outputsFor(e);
152
152
  const contract = {
153
- purpose: e.purpose ?? { summary: e.summary },
153
+ purpose: e.purpose ? { ...e.purpose, summary: e.purpose.summary ?? e.summary } : { summary: e.summary },
154
154
  params: {
155
155
  required: e.params.map((p) => ({ name: p.name, description: p.description, example: p.example })),
156
156
  one_of: e.oneOfGroups,
@@ -217,7 +217,7 @@ export function contractFor(e) {
217
217
  * next, freshness). Every block is checked; a malformed one is skipped, never
218
218
  * thrown on. True when anything was used.
219
219
  */
220
- function overlay(contract, data) {
220
+ function overlay(contract, data, bundledPaths = []) {
221
221
  let used = false;
222
222
  const cost = contract.cost;
223
223
  if (isObj(data.credits)) {
@@ -237,8 +237,12 @@ function overlay(contract, data) {
237
237
  (contract.purpose = c.purpose), (used = true);
238
238
  if (isObj(c.outputs)) {
239
239
  const fields = cleanFields(c.outputs.fields);
240
- if (fields.length > 0 || c.outputs.source === "unknown") {
241
- const prev = contract.outputs;
240
+ const prev = contract.outputs;
241
+ // A deployed API can lag this release's field list: a live list that is empty, or only a
242
+ // part of the bundled one, would hide fields this server already knows. Keep the bundled list then.
243
+ const bundled = new Set(bundledPaths);
244
+ const stale = bundled.size > 0 && fields.length < bundled.size && fields.every((f) => bundled.has(f.path));
245
+ if ((fields.length > 0 || c.outputs.source === "unknown") && !stale) {
242
246
  contract.outputs = {
243
247
  archetype: str(c.outputs.archetype) ?? prev.archetype,
244
248
  rows_at: str(c.outputs.rows_at) ?? prev.rows_at ?? null,
@@ -339,7 +343,7 @@ export async function endpointStructured(ctx, params) {
339
343
  const e = resolved.endpoint;
340
344
  const contract = contractFor(e);
341
345
  const live = await liveGuide(ctx, e);
342
- const isLive = live !== undefined && overlay(contract, live);
346
+ const isLive = live !== undefined && overlay(contract, live, (outputsFor(e)?.fields ?? []).map((f) => f.path));
343
347
  const id = `${e.platform}/${e.resource}`;
344
348
  const structured = { ok: true, id, method: e.method, source: isLive ? "live" : "bundled", contract };
345
349
  return { text: render(id, e, contract, isLive), structured };
@@ -3,7 +3,7 @@ import { fetchEstimateData, fetchPlanEstimate, localQuote } from "../cost-guard.
3
3
  import { errorFromText } from "../result.js";
4
4
  import { suggestEndpoints, suggestPlatforms } from "../search/catalog.js";
5
5
  import { normalizeEndpointId } from "./discover.js";
6
- import { pricingStructured } from "./pricing.js";
6
+ import { pricingStructured, v2Wording } from "./pricing.js";
7
7
  import { resolveEndpoint, stringifyParams } from "./request.js";
8
8
  import { walkQuote } from "../walk-quote.js";
9
9
  const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
@@ -49,12 +49,40 @@ async function single(ctx, input, e) {
49
49
  ...(typeof data.formula === "string" ? { formula: data.formula } : {}),
50
50
  ...(Array.isArray(data.levers) && data.levers.length > 0 ? { levers: data.levers } : {}),
51
51
  ...(isObj(data.rejection) ? { rejection: data.rejection } : {}),
52
- ...(data.items !== undefined ? { items: data.items } : {}),
53
52
  calls,
54
53
  total_hold: hold * calls,
55
54
  };
56
- const warnings = Array.isArray(data.warnings) ? data.warnings.map(String) : [];
57
- return { text: renderApi(quote, warnings), structured: { ok: true, source: "api", quote, ...(warnings.length ? { warnings } : {}) } };
55
+ // The API's own walk block can carry a null max; the walk below replaces it.
56
+ const warnings = (Array.isArray(data.warnings) ? data.warnings.map(String) : []).filter((w) => !UNPROVEN.test(w));
57
+ // The API ignores `items`: apply the same items -> pages walk, priced per page by the API's own quote.
58
+ let source = "api";
59
+ if (input.items !== undefined) {
60
+ const walk = walkQuote(e, input.items);
61
+ const w = walk.quote;
62
+ if (w) {
63
+ const perMin = num(data.expected_min) ?? hold;
64
+ const perMax = num(data.expected_max) ?? hold;
65
+ const lo = w.pages * perMin;
66
+ const hi = w.pages * perMax;
67
+ const perPageHold = hold;
68
+ const total = w.pages * perPageHold;
69
+ Object.assign(quote, {
70
+ hold: total,
71
+ pages: w.pages,
72
+ page_size: w.page_size,
73
+ price_basis: w.price_basis,
74
+ expected_min: lo,
75
+ expected_max: hi,
76
+ formula: `${input.items} items: ${w.pages} pages x ${perMin === perMax ? perMax : `${perMin}-${perMax}`} = ${lo === hi ? hi : `${lo}-${hi}`} credits.`,
77
+ walk: { pages: w.pages, page_size: w.page_size, per_page_hold: perPageHold, per_page_min: perMin, per_page_max: perMax },
78
+ items: { n: input.items, pages: w.pages, page_size: w.page_size, credits_min: lo, credits_max: hi },
79
+ total_hold: total * calls,
80
+ });
81
+ source = "api+walk";
82
+ }
83
+ warnings.push(...walkWarnings(walk.warnings, w ? { pages: w.pages, per: perPageRange(num(data.expected_min) ?? hold, num(data.expected_max) ?? hold) } : undefined));
84
+ }
85
+ return { text: renderApi(quote, warnings), structured: { ok: true, source, quote, ...(warnings.length ? { warnings } : {}) } };
58
86
  }
59
87
  }
60
88
  const priced = pricingStructured({
@@ -87,16 +115,32 @@ async function single(ctx, input, e) {
87
115
  calls,
88
116
  total_hold: perCall * calls,
89
117
  };
90
- const warnings = walk.warnings;
118
+ const warnings = walkWarnings(walk.warnings, w ? { pages: w.pages, per: perPageRange(w.expected_min / w.pages, w.expected_max / w.pages) } : undefined);
91
119
  const head = `Local quote for ${id}: holds up to ${perCall} credits per call${w ? ` (${w.pages} pages)` : ""}${calls > 1 ? `, ${perCall * calls} for ${calls} calls` : ""}. The settled charge is refunded down to the work done.`;
92
120
  return {
93
- text: [head, ...(w ? [`Walk: ${w.formula}`] : []), ...warnings, "", priced.text].join("\n"),
121
+ text: [head, ...(w ? [`Walk: ${w.formula}`] : []), ...warnings, "", v2Wording(priced.text)].join("\n"),
94
122
  structured: { ok: true, source: "local", quote, ...(warnings.length ? { warnings } : {}) },
95
123
  };
96
124
  }
125
+ /** The registry's "per-page price is not proven" notes (the API's and ours). */
126
+ const UNPROVEN = /^price_basis_unknown\b/;
127
+ const perPageRange = (min, max) => (min === max ? `${max}` : `${min}-${max}`);
128
+ /**
129
+ * A walk's warnings with the "per-page price is not proven" notes (which also
130
+ * say the max is null) folded into one caveat: the quote stands on the
131
+ * one-call price, and the caveat says how far to trust it.
132
+ */
133
+ function walkWarnings(warnings, walk) {
134
+ const unproven = warnings.some((w) => UNPROVEN.test(w));
135
+ const rest = warnings.filter((w) => !UNPROVEN.test(w));
136
+ if (unproven && walk) {
137
+ rest.push(`walk: priced as ${walk.pages} pages x the one-call quote (${walk.per} credits each); a page's price is not proven, so check credits_used as pages arrive.`);
138
+ }
139
+ return rest;
140
+ }
97
141
  function renderApi(q, warnings) {
98
142
  const lines = [
99
- `Quote for ${String(q.endpoint)} (API): holds ${String(q.hold)} credits${q.expected_min !== undefined ? `; expect ${String(q.expected_min)}-${String(q.expected_max)} after refunds` : ""}.`,
143
+ `Quote for ${String(q.endpoint)} (API): holds ${String(q.hold)} credits${q.pages !== undefined ? ` (${String(q.pages)} pages)` : ""}${q.expected_min !== undefined ? `; expect ${String(q.expected_min)}-${String(q.expected_max)} after refunds` : ""}.`,
100
144
  ];
101
145
  if (q.valid === false) {
102
146
  const r = q.rejection;
@@ -172,7 +216,7 @@ export async function estimateStructured(ctx, input) {
172
216
  return plan(ctx, input.plan);
173
217
  if (!input.id) {
174
218
  const o = pricingStructured({ action: "overview" });
175
- return { text: o.text, structured: { ok: true, source: "local" } };
219
+ return { text: v2Wording(o.text), structured: { ok: true, source: "local" } };
176
220
  }
177
221
  const key = normalizeEndpointId(input.id);
178
222
  if (!key.includes("/")) {
@@ -181,7 +225,7 @@ export async function estimateStructured(ctx, input) {
181
225
  return errorOutput("error" in hit ? hit.error : `Error: Unknown platform "${key}".`);
182
226
  }
183
227
  const t = pricingStructured({ action: "platform", platform: key });
184
- return { text: t.text, structured: { ok: true, source: "local" } };
228
+ return { text: v2Wording(t.text), structured: { ok: true, source: "local" } };
185
229
  }
186
230
  const hit = lookup(key, input.method);
187
231
  if ("error" in hit)
@@ -28,7 +28,11 @@ interface TaskFacts {
28
28
  /** The task with URLs and handles taken out, plus the URLs' platform names, for the ranker. */
29
29
  rankQuery: string;
30
30
  urlPlatforms: string[];
31
+ /** The task with URLs and handles taken out (intent words are read here, never inside a URL). */
32
+ text: string;
31
33
  }
32
34
  export declare function readTask(task: string): TaskFacts;
33
35
  export declare function findStructured(ctx: ApiContext, params: FindParams): Promise<ToolOutput>;
36
+ /** Read on the task's words only: URLs and handles are taken out first (a YouTube `watch?v=` is not intent). */
37
+ export declare const wantsMonitor: (task: string) => boolean;
34
38
  export {};