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,58 @@
1
1
  import { csvHeader, csvLines, flattenRows, toCsv } from "./csv.js";
2
2
  import { emptyProjectionWarning, isEmptyProjection, looksProjected, parseFields, pathMatches, projectValue, rowRoots, withIdentity } from "./fields.js";
3
+ /** Ever tighter caps for a main object that does not fit: [array items, string characters]. */
4
+ const TRIM_LEVELS = [[50, 2000], [20, 500], [10, 200], [5, 100], [2, 60], [1, 30]];
5
+ /** A copy with every array capped at `items` and every string cut at `chars` (with "…"). */
6
+ function trimValue(v, items, chars, depth = 0) {
7
+ if (typeof v === "string")
8
+ return v.length > chars ? `${v.slice(0, chars)}…` : v;
9
+ if (Array.isArray(v))
10
+ return v.slice(0, items).map((x) => trimValue(x, items, chars, depth + 1));
11
+ if (isObject(v)) {
12
+ if (depth > 6)
13
+ return "…";
14
+ const out = {};
15
+ for (const [k, x] of Object.entries(v))
16
+ out[k] = trimValue(x, items, chars, depth + 1);
17
+ return out;
18
+ }
19
+ return v;
20
+ }
21
+ /**
22
+ * A single object that does not fit, cut around its main object: the main
23
+ * object stays (trimmed if it must be), then the other top-level keys of
24
+ * `data` in order while they fit; the rest are omitted.
25
+ */
26
+ function keepMain(env, data, main, budget) {
27
+ const base = size({ ...env, data: {} });
28
+ let value = data[main];
29
+ let note;
30
+ if (base + size(main) + size(value) + 2 > budget) {
31
+ for (const [items, chars] of TRIM_LEVELS) {
32
+ value = trimValue(data[main], items, chars);
33
+ note = `data.${main} trimmed to fit: arrays capped at ${items} item${items === 1 ? "" : "s"}, strings cut at ${chars} characters (the full body is behind the result link).`;
34
+ if (base + size(main) + size(value) + 2 <= budget)
35
+ break;
36
+ }
37
+ }
38
+ let used = base + size(main) + size(value) + 2;
39
+ const kept = {};
40
+ const omitted = [];
41
+ for (const [k, v] of Object.entries(data)) {
42
+ if (k === main) {
43
+ kept[k] = value;
44
+ continue;
45
+ }
46
+ const c = size(k) + size(v) + 2;
47
+ if (used + c <= budget) {
48
+ kept[k] = v;
49
+ used += c;
50
+ }
51
+ else
52
+ omitted.push(k);
53
+ }
54
+ return { envelope: { ...env, data: kept }, omitted, ...(note ? { note } : {}) };
55
+ }
3
56
  const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
4
57
  const size = (v) => JSON.stringify(v).length;
5
58
  /** Where an envelope keeps its rows: `data.items` or a bare `data` array. */
@@ -181,6 +234,17 @@ export function shapeEnvelope(parsed, opts) {
181
234
  return { envelope: shownEnv, total, shown: n, cut, projected, ...extra };
182
235
  }
183
236
  // A single object (or scalar): cut at top-level keys of `data` when it is too big.
237
+ // The main object (the contract's, or the only key) is kept and trimmed, never omitted.
238
+ const dataObj = isObject(env.data) ? env.data : undefined;
239
+ const keys = dataObj ? Object.keys(dataObj).filter((k) => k !== "_warnings") : [];
240
+ const main = dataObj && opts.mainKey && opts.mainKey in dataObj ? opts.mainKey : keys.length === 1 && isObject(dataObj?.[keys[0]]) ? keys[0] : undefined;
241
+ if (dataObj && main && size(env) > opts.budget) {
242
+ const r = keepMain(env, dataObj, main, opts.budget);
243
+ if (size(r.envelope) <= opts.budget) {
244
+ const notes = [...warnings, ...(r.note ? [r.note] : [])];
245
+ return { envelope: r.envelope, cut: true, projected, omittedKeys: r.omitted, ...(notes.length > 0 ? { warnings: notes } : {}) };
246
+ }
247
+ }
184
248
  if (isObject(env.data) && size(env) > opts.budget) {
185
249
  const kept = {};
186
250
  const omitted = [];
@@ -1,15 +1,15 @@
1
1
  import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
2
2
  import type { ApiContext } from "./context.js";
3
3
  /**
4
- * Is the bundled catalogue behind the live registry? Checked once per process
5
- * and base URL (stdio: at startup; HTTP: on the first request), never blocking
4
+ * Is the bundled catalogue behind the live registry? Checked per base URL at
5
+ * most once every FRESHNESS_TTL_MS (stdio: at startup; HTTP: on a request), never blocking
6
6
  * a tool call, and silent when offline, keyless or on any error.
7
7
  *
8
8
  * Preferred probe: `GET /v1/utility/endpoints?fingerprint=1` -> `{fingerprint}`,
9
9
  * compared with the bundled SHA-256 (it catches a changed parameter, not just a
10
10
  * new endpoint). That route is not deployed everywhere yet, so on 404 or any
11
- * other failure we fall back to the count comparison `socialcrawl_discover`
12
- * `action: "freshness"` uses.
11
+ * other failure we fall back to comparing platform and endpoint counts.
12
+ * `socialcrawl_account` view freshness renders the same check.
13
13
  */
14
14
  export declare const STALE_LINE = "Note: this server's bundled endpoint catalogue is behind the live registry; calls use the live registry. For current endpoints use socialcrawl_endpoint (live with a key) and update socialcrawl-mcp.";
15
15
  export type Freshness = "fresh" | "stale" | "unknown";
@@ -17,7 +17,30 @@ export interface ProbeOptions {
17
17
  fetchImpl?: typeof fetch;
18
18
  timeoutMs?: number;
19
19
  }
20
+ /** What one freshness check found: the verdict, what it rests on, and the live numbers it saw. */
21
+ export interface FreshnessReport {
22
+ state: Freshness;
23
+ /** `fingerprint` when the live registry fingerprint was compared; `counts` on the fallback. */
24
+ basis?: "fingerprint" | "counts";
25
+ live?: {
26
+ fingerprint?: string;
27
+ platforms?: number;
28
+ endpoints?: number;
29
+ };
30
+ }
31
+ /**
32
+ * THE freshness check, shared by `socialcrawl_account` view freshness and the
33
+ * one-line stale note on tool results, so the two can never disagree. The
34
+ * live registry fingerprint decides when the API publishes one; the platform
35
+ * and endpoint counts decide otherwise.
36
+ */
37
+ export declare function checkFreshness(ctx: ApiContext, opts?: ProbeOptions): Promise<FreshnessReport>;
20
38
  export declare function probeFreshness(ctx: ApiContext, opts?: ProbeOptions): Promise<Freshness>;
39
+ /**
40
+ * How long one answer stands. A long-running server (the hosted HTTP one)
41
+ * must notice when the API it talks to is redeployed, so an answer expires.
42
+ */
43
+ export declare const FRESHNESS_TTL_MS: number;
21
44
  /** Test hook: forget every completed check. */
22
45
  export declare function resetFreshness(): void;
23
46
  /**
package/dist/freshness.js CHANGED
@@ -1,14 +1,14 @@
1
1
  import { REGISTRY_FINGERPRINT, REGISTRY_STATS } from "./data/registry-meta.js";
2
2
  /**
3
- * Is the bundled catalogue behind the live registry? Checked once per process
4
- * and base URL (stdio: at startup; HTTP: on the first request), never blocking
3
+ * Is the bundled catalogue behind the live registry? Checked per base URL at
4
+ * most once every FRESHNESS_TTL_MS (stdio: at startup; HTTP: on a request), never blocking
5
5
  * a tool call, and silent when offline, keyless or on any error.
6
6
  *
7
7
  * Preferred probe: `GET /v1/utility/endpoints?fingerprint=1` -> `{fingerprint}`,
8
8
  * compared with the bundled SHA-256 (it catches a changed parameter, not just a
9
9
  * new endpoint). That route is not deployed everywhere yet, so on 404 or any
10
- * other failure we fall back to the count comparison `socialcrawl_discover`
11
- * `action: "freshness"` uses.
10
+ * other failure we fall back to comparing platform and endpoint counts.
11
+ * `socialcrawl_account` view freshness renders the same check.
12
12
  */
13
13
  export const STALE_LINE = "Note: this server's bundled endpoint catalogue is behind the live registry; calls use the live registry. For current endpoints use socialcrawl_endpoint (live with a key) and update socialcrawl-mcp.";
14
14
  const DEFAULT_TIMEOUT_MS = 2500;
@@ -31,23 +31,45 @@ async function getJson(url, ctx, opts) {
31
31
  clearTimeout(timer);
32
32
  }
33
33
  }
34
- export async function probeFreshness(ctx, opts = {}) {
34
+ const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : undefined);
35
+ /**
36
+ * THE freshness check, shared by `socialcrawl_account` view freshness and the
37
+ * one-line stale note on tool results, so the two can never disagree. The
38
+ * live registry fingerprint decides when the API publishes one; the platform
39
+ * and endpoint counts decide otherwise.
40
+ */
41
+ export async function checkFreshness(ctx, opts = {}) {
35
42
  if (!ctx.apiKey)
36
- return "unknown";
43
+ return { state: "unknown" };
37
44
  const endpoint = `${ctx.baseUrl}/v1/utility/endpoints`;
38
45
  const fp = await getJson(`${endpoint}?fingerprint=1`, ctx, opts);
39
- const live = isObject(fp?.data) ? fp.data.fingerprint : fp?.fingerprint;
40
- if (typeof live === "string" && live)
41
- return live === REGISTRY_FINGERPRINT ? "fresh" : "stale";
46
+ const fpData = isObject(fp?.data) ? fp.data : fp;
47
+ const live = fpData?.fingerprint;
48
+ if (typeof live === "string" && live) {
49
+ return {
50
+ state: live === REGISTRY_FINGERPRINT ? "fresh" : "stale",
51
+ basis: "fingerprint",
52
+ live: { fingerprint: live, platforms: num(fpData?.platforms), endpoints: num(fpData?.endpoints) },
53
+ };
54
+ }
42
55
  const counts = await getJson(`${endpoint}?search=${encodeURIComponent(" freshness-probe")}`, ctx, opts);
43
56
  const data = isObject(counts?.data) ? counts.data : undefined;
44
57
  const stats = isObject(data?.stats) ? data.stats : undefined;
45
- if (typeof stats?.endpoints !== "number" || typeof stats.platforms !== "number")
46
- return "unknown";
47
- return stats.endpoints === REGISTRY_STATS.totalEndpoints && stats.platforms === REGISTRY_STATS.totalPlatforms
48
- ? "fresh"
49
- : "stale";
58
+ const platforms = num(stats?.platforms);
59
+ const endpoints = num(stats?.endpoints);
60
+ if (platforms === undefined || endpoints === undefined)
61
+ return { state: "unknown" };
62
+ const same = endpoints === REGISTRY_STATS.totalEndpoints && platforms === REGISTRY_STATS.totalPlatforms;
63
+ return { state: same ? "fresh" : "stale", basis: "counts", live: { platforms, endpoints } };
50
64
  }
65
+ export async function probeFreshness(ctx, opts = {}) {
66
+ return (await checkFreshness(ctx, opts)).state;
67
+ }
68
+ /**
69
+ * How long one answer stands. A long-running server (the hosted HTTP one)
70
+ * must notice when the API it talks to is redeployed, so an answer expires.
71
+ */
72
+ export const FRESHNESS_TTL_MS = 10 * 60 * 1000;
51
73
  const checks = new Map();
52
74
  const NO = Promise.resolve(false);
53
75
  /** Test hook: forget every completed check. */
@@ -65,11 +87,12 @@ export function startFreshnessCheck(ctx) {
65
87
  return NO;
66
88
  if (!ctx.apiKey)
67
89
  return NO;
68
- let check = checks.get(ctx.baseUrl);
69
- if (!check) {
70
- check = probeFreshness(ctx).then((r) => r === "stale", () => false);
71
- checks.set(ctx.baseUrl, check);
72
- }
90
+ const now = Date.now();
91
+ const cached = checks.get(ctx.baseUrl);
92
+ if (cached && now - cached.at < FRESHNESS_TTL_MS)
93
+ return cached.check;
94
+ const check = probeFreshness(ctx).then((r) => r === "stale", () => false);
95
+ checks.set(ctx.baseUrl, { at: now, check });
73
96
  return check;
74
97
  }
75
98
  /** Append the stale line to a result's text and, when it has structured output, to `warnings`. */
@@ -22,11 +22,18 @@ export function createJwtVerifier(options) {
22
22
  algorithms: options.algorithms ?? DEFAULT_ALGORITHMS,
23
23
  requiredClaims: ["exp"],
24
24
  clockTolerance: options.clockToleranceSec ?? 30,
25
+ // RFC 9068. The authorization server signs other JWTs with the same
26
+ // key (Better Auth's session JWTs); only access tokens may pass.
27
+ typ: "at+jwt",
25
28
  }));
26
29
  }
27
30
  catch (error) {
28
31
  throw toAuthError(error);
29
32
  }
33
+ // A DPoP-bound token is only safe with a proof check, which this server
34
+ // does not do, so it is refused rather than accepted as a bearer token.
35
+ if (payload.cnf !== undefined)
36
+ throw new InvalidTokenError("Sender-constrained tokens are not supported");
30
37
  return {
31
38
  token,
32
39
  clientId: stringClaim(payload.client_id) ?? stringClaim(payload.azp) ?? "",
@@ -16,7 +16,9 @@ export declare function mountProtectedResourceMetadata(app: express.Express, con
16
16
  * → resolve the SocialCrawl API key (401 if unlinked).
17
17
  * - x-api-key, or a non-JWT Bearer value → unchanged API-key path, so
18
18
  * headless clients keep working.
19
- * - no credentials → 401 + `WWW-Authenticate: Bearer resource_metadata=…`
19
+ * - no credentials → initialize, tools/list and the free discovery tools
20
+ * run anonymously; a call that needs an account gets
21
+ * 401 + `WWW-Authenticate: Bearer resource_metadata=…`
20
22
  * so connector clients (claude.ai) start the OAuth flow.
21
23
  *
22
24
  * SECURITY: nothing here logs or echoes the token or the resolved key.
@@ -2,7 +2,7 @@ import { requireBearerAuth } from "@modelcontextprotocol/sdk/server/auth/middlew
2
2
  import { metadataHandler } from "@modelcontextprotocol/sdk/server/auth/handlers/metadata.js";
3
3
  import { getOAuthProtectedResourceMetadataUrl } from "@modelcontextprotocol/sdk/server/auth/router.js";
4
4
  import { extractApiKey, extractBearerToken, isJwtShaped } from "../auth.js";
5
- import { SCOPES_SUPPORTED, missingScopesForBody } from "./scopes.js";
5
+ import { SCOPES_SUPPORTED, missingScopesForBody, needsSignIn } from "./scopes.js";
6
6
  import { ApiKeyLookupUnavailableError } from "./api-key-resolver.js";
7
7
  const ROOT_METADATA_PATH = "/.well-known/oauth-protected-resource";
8
8
  /** `res.locals` slot the gate fills with the API key a verified token maps to. */
@@ -34,7 +34,9 @@ export function mountProtectedResourceMetadata(app, config) {
34
34
  * → resolve the SocialCrawl API key (401 if unlinked).
35
35
  * - x-api-key, or a non-JWT Bearer value → unchanged API-key path, so
36
36
  * headless clients keep working.
37
- * - no credentials → 401 + `WWW-Authenticate: Bearer resource_metadata=…`
37
+ * - no credentials → initialize, tools/list and the free discovery tools
38
+ * run anonymously; a call that needs an account gets
39
+ * 401 + `WWW-Authenticate: Bearer resource_metadata=…`
38
40
  * so connector clients (claude.ai) start the OAuth flow.
39
41
  *
40
42
  * SECURITY: nothing here logs or echoes the token or the resolved key.
@@ -48,6 +50,14 @@ export function oauthGate(config) {
48
50
  next();
49
51
  return;
50
52
  }
53
+ // Lazy authentication: anonymous discovery keeps working, and only a
54
+ // call that needs an account gets the 401. The challenge has to be an
55
+ // HTTP 401 sent before the SDK runs; a tool result would be a 200, and
56
+ // clients only start sign-in on the 401.
57
+ if (req.is("application/json") && req.body !== undefined && !needsSignIn(req.body)) {
58
+ next();
59
+ return;
60
+ }
51
61
  res.set("WWW-Authenticate", `Bearer resource_metadata="${resourceMetadataUrl}", scope="${SCOPES_SUPPORTED.join(" ")}"`);
52
62
  res.status(401).json({
53
63
  jsonrpc: "2.0",
@@ -18,6 +18,19 @@ export declare const SCOPES_SUPPORTED: string[];
18
18
  * first, then the 1.x names `SOCIALCRAWL_LEGACY_TOOLS=1` brings back.
19
19
  */
20
20
  export declare const TOOL_SCOPES: Record<string, readonly string[]>;
21
+ /**
22
+ * Tools that work with no API key at all (free, local discovery). With OAuth
23
+ * on, an anonymous caller may use these, initialize and tools/list; anything
24
+ * else gets the 401 challenge that starts sign-in (lazy authentication).
25
+ */
26
+ export declare const ANONYMOUS_TOOLS: ReadonlySet<string>;
27
+ /**
28
+ * True when an anonymous JSON-RPC body (single message or batch) contains a
29
+ * tools/call that needs an API key. Fails closed like missingScopesForBody: a
30
+ * body that is not a parsed JSON-RPC object, a nameless call or an unknown
31
+ * tool all need sign-in.
32
+ */
33
+ export declare function needsSignIn(body: unknown): boolean;
21
34
  /** Scopes a tool needs. Unknown tools fail closed and need every scope. */
22
35
  export declare function requiredScopesForTool(name: string): readonly string[];
23
36
  /**
@@ -36,6 +36,39 @@ export const TOOL_SCOPES = {
36
36
  socialcrawl_monitors: [SCOPES.spend, SCOPES.manage],
37
37
  socialcrawl_cohorts: [SCOPES.spend, SCOPES.manage],
38
38
  };
39
+ /**
40
+ * Tools that work with no API key at all (free, local discovery). With OAuth
41
+ * on, an anonymous caller may use these, initialize and tools/list; anything
42
+ * else gets the 401 challenge that starts sign-in (lazy authentication).
43
+ */
44
+ export const ANONYMOUS_TOOLS = new Set([
45
+ "socialcrawl_find",
46
+ "socialcrawl_endpoint",
47
+ "socialcrawl_estimate",
48
+ // 1.x names (legacy flag).
49
+ "socialcrawl_list_platforms",
50
+ "socialcrawl_list_endpoints",
51
+ "socialcrawl_pricing",
52
+ "socialcrawl_discover",
53
+ "socialcrawl_get_docs",
54
+ ]);
55
+ /**
56
+ * True when an anonymous JSON-RPC body (single message or batch) contains a
57
+ * tools/call that needs an API key. Fails closed like missingScopesForBody: a
58
+ * body that is not a parsed JSON-RPC object, a nameless call or an unknown
59
+ * tool all need sign-in.
60
+ */
61
+ export function needsSignIn(body) {
62
+ const messages = Array.isArray(body) ? body : [body];
63
+ return messages.some((message) => {
64
+ if (typeof message !== "object" || message === null || Array.isArray(message))
65
+ return true;
66
+ if (message.method !== "tools/call")
67
+ return false;
68
+ const name = message.params?.name;
69
+ return typeof name !== "string" || !ANONYMOUS_TOOLS.has(name);
70
+ });
71
+ }
39
72
  /** Scopes a tool needs. Unknown tools fail closed and need every scope. */
40
73
  export function requiredScopesForTool(name) {
41
74
  return Object.hasOwn(TOOL_SCOPES, name) ? TOOL_SCOPES[name] : SCOPES_SUPPORTED;
package/dist/result.d.ts CHANGED
@@ -35,6 +35,8 @@ export declare function errorFromText(text: string): Json;
35
35
  * `page`; a non-list `data` is passed through whole.
36
36
  */
37
37
  export declare function structureEnvelope(env: unknown, quotedMax?: number): Json;
38
+ /** A cursor short enough to print, or its head with "…" (the full value stays in structuredContent). */
39
+ export declare function shortCursor(cursor: string, max?: number): string;
38
40
  /** The 2-4 line human summary that heads the compact JSON in `content`. */
39
41
  export declare function summaryLine(s: Json): string;
40
42
  export {};
package/dist/result.js CHANGED
@@ -64,6 +64,8 @@ const FIXES = {
64
64
  NETWORK_ERROR: "Check connectivity to the API, then retry.",
65
65
  WRONG_TOOL: "Use socialcrawl_manage with area web for the web platform.",
66
66
  VALIDATION_ERROR: "Apply did_you_mean or the correction in reason; a 400 is not charged.",
67
+ RESULT_EXPIRED: "Repeat the request or walk; a cached repeat is free.",
68
+ DRY_RUN_UNSUPPORTED: "Nothing was kept. Check the fields yourself, or create it for real without dry_run.",
67
69
  };
68
70
  const STATUS_CODES = {
69
71
  400: "BAD_REQUEST", 401: "UNAUTHORIZED", 402: "INSUFFICIENT_CREDITS", 404: "NOT_FOUND",
@@ -81,6 +83,8 @@ const LOCAL_CODES = [
81
83
  [/^Error: The "web" platform/, "WRONG_TOOL", false],
82
84
  [/^Error: Request timed out/, "TIMEOUT", true],
83
85
  [/^Error: Could not reach/, "NETWORK_ERROR", true],
86
+ [/^Error: No stored result/, "RESULT_EXPIRED", false],
87
+ [/^Error: dry_run/, "DRY_RUN_UNSUPPORTED", false],
84
88
  ];
85
89
  /**
86
90
  * Turn the error text every tool produces into the structured error shape.
@@ -212,6 +216,10 @@ export function structureEnvelope(env, quotedMax) {
212
216
  }
213
217
  return out;
214
218
  }
219
+ /** A cursor short enough to print, or its head with "…" (the full value stays in structuredContent). */
220
+ export function shortCursor(cursor, max = 64) {
221
+ return cursor.length <= max ? cursor : `${cursor.slice(0, max)}…`;
222
+ }
215
223
  /** The 2-4 line human summary that heads the compact JSON in `content`. */
216
224
  export function summaryLine(s) {
217
225
  const credits = (s.credits ?? {});
@@ -0,0 +1,27 @@
1
+ import type { AnyZodObject, ZodEffects } from "zod";
2
+ /**
3
+ * One input preprocessor for every tool, so an agent that learned one tool's
4
+ * argument shape can use it on the others. It runs before the tool's own
5
+ * strict schema (which stays the compact shape the tool advertises):
6
+ *
7
+ * - An endpoint is named any of three ways: `id: "platform/resource"`,
8
+ * `platform` + `resource`, or `path: "/v1/platform/resource"` (a full URL
9
+ * works too). Each tool receives its own form: `socialcrawl_request` gets
10
+ * platform + resource, the others get `id`. `estimate.plan[]` entries too.
11
+ * - `fields` takes a comma string or an array of strings.
12
+ * - `estimate.calls` given an array is the plan.
13
+ * - `collect` given `limit` and no `items` (and no `result_id`) walks to that many.
14
+ * - An unknown key is refused with the key to use instead, not a bare
15
+ * `unrecognized_keys`.
16
+ */
17
+ export type ToolKind = "find" | "endpoint" | "estimate" | "request" | "collect" | "account" | "manage";
18
+ /** `"/v1/tiktok/profile"`, a full URL, or `"tiktok/profile"` -> `"tiktok/profile"`. */
19
+ export declare function endpointKey(raw: string): string;
20
+ /** The argument object normalised for `kind` (without the unknown-key check). */
21
+ export declare function normalizeArgs(kind: ToolKind, raw: unknown): unknown;
22
+ /**
23
+ * `schema` with the preprocessor in front. The result still advertises the
24
+ * object's own JSON Schema (the SDK lists `shape`, and the converter reads a
25
+ * preprocess as its inner schema), so the tool's listed schema does not grow.
26
+ */
27
+ export declare function withNormalizedArgs<T extends AnyZodObject>(schema: T, kind: ToolKind): ZodEffects<T>;
@@ -0,0 +1,189 @@
1
+ import { z } from "zod";
2
+ import { MOVED_PARAMS_KEY } from "../constants.js";
3
+ import { resolveEndpoint } from "../endpoint-resolve.js";
4
+ /** How a tool wants the endpoint named, or none for tools that do not name one. */
5
+ const NAMING = {
6
+ endpoint: "id",
7
+ estimate: "id",
8
+ request: "platform+resource",
9
+ collect: "id",
10
+ };
11
+ /** Wrong keys agents reach for, and what to use instead. */
12
+ const ENDPOINT_HINT = 'use id, or platform+resource (or path: "/v1/platform/resource")';
13
+ const ENDPOINT_ALIASES = new Set(["endpoint", "endpoint_id", "route", "name", "slug"]);
14
+ const ALIASES = {
15
+ url: "put the URL in params, e.g. params: { url }",
16
+ query: "put query params in params",
17
+ parameters: "use params",
18
+ param: "use params",
19
+ args: "use params",
20
+ arguments: "use params",
21
+ query_params: "use params",
22
+ payload: "use body",
23
+ data: "use body",
24
+ json: "use body",
25
+ };
26
+ const PER_TOOL = {
27
+ find: { query: "use task", q: "use task", prompt: "use task", search: "use task", text: "use task", description: "use task" },
28
+ collect: { max_items: "use items (rows to collect)", count: "use items", n: "use items", rows: "use items", total: "use items", max_rows: "use items" },
29
+ request: { limit: "put limit in params", items: "use socialcrawl_collect to walk pages to N items", count: "use max_items" },
30
+ estimate: { count: "use calls", repeat: "use calls", n: "use calls" },
31
+ manage: { body: "use input", params: "use input", data: "use input" },
32
+ };
33
+ const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
34
+ /** `"/v1/tiktok/profile"`, a full URL, or `"tiktok/profile"` -> `"tiktok/profile"`. */
35
+ export function endpointKey(raw) {
36
+ let s = raw.trim().replace(/^https?:\/\/[^/]*/i, "");
37
+ const cut = s.search(/[?#]/);
38
+ if (cut !== -1)
39
+ s = s.slice(0, cut);
40
+ s = s.replace(/^\/+/, "").replace(/\/+$/, "");
41
+ if (s.startsWith("v1/"))
42
+ s = s.slice(3);
43
+ return s;
44
+ }
45
+ /**
46
+ * The endpoint an argument object names, as a key ("platform/resource", or a
47
+ * bare platform), or undefined when it names none. Precedence: id, path, platform + resource.
48
+ */
49
+ function namedEndpoint(a) {
50
+ if (typeof a.id === "string" && a.id.trim())
51
+ return endpointKey(a.id);
52
+ if (typeof a.path === "string" && a.path.trim())
53
+ return endpointKey(a.path);
54
+ if (typeof a.platform === "string" && a.platform.trim()) {
55
+ const resource = typeof a.resource === "string" ? endpointKey(a.resource) : "";
56
+ return resource ? `${a.platform.trim()}/${resource}` : a.platform.trim();
57
+ }
58
+ return undefined;
59
+ }
60
+ /** Rewrite one endpoint-naming argument object into `form`. */
61
+ function renameEndpoint(a, form) {
62
+ const key = namedEndpoint(a);
63
+ const out = { ...a };
64
+ delete out.path;
65
+ if (key === undefined)
66
+ return out;
67
+ delete out.id;
68
+ delete out.platform;
69
+ delete out.resource;
70
+ if (form === "id")
71
+ return { ...out, id: key };
72
+ const slash = key.indexOf("/");
73
+ return slash === -1 ? { ...out, platform: key } : { ...out, platform: key.slice(0, slash), resource: key.slice(slash + 1) };
74
+ }
75
+ const fieldsString = (v) => Array.isArray(v) && v.every((x) => typeof x === "string") ? v.map((s) => s.trim()).filter(Boolean).join(",") : v;
76
+ /** The argument object normalised for `kind` (without the unknown-key check). */
77
+ export function normalizeArgs(kind, raw) {
78
+ if (!isObj(raw))
79
+ return raw;
80
+ let a = { ...raw };
81
+ if (kind === "estimate" && Array.isArray(a.calls)) {
82
+ if (a.plan === undefined)
83
+ a.plan = a.calls;
84
+ delete a.calls;
85
+ }
86
+ if (kind === "estimate" && Array.isArray(a.plan)) {
87
+ a.plan = a.plan.map((c) => (isObj(c) ? renameEndpoint(c, "id") : c));
88
+ }
89
+ if (kind === "collect" && a.result_id === undefined && a.items === undefined && typeof a.limit === "number") {
90
+ a.items = a.limit;
91
+ delete a.limit;
92
+ }
93
+ if (kind === "account") {
94
+ if (a.view === undefined && a.action !== undefined) {
95
+ a.view = a.action;
96
+ delete a.action;
97
+ }
98
+ if (typeof a.view === "string")
99
+ a.view = VIEW_ALIASES[a.view.toLowerCase()] ?? a.view;
100
+ }
101
+ // find's `platform` is a filter, not an endpoint name.
102
+ const form = NAMING[kind];
103
+ if (form)
104
+ a = renameEndpoint(a, form);
105
+ if ("fields" in a)
106
+ a.fields = fieldsString(a.fields);
107
+ return a;
108
+ }
109
+ const VIEW_ALIASES = { ledger: "transactions", history: "transactions", transaction: "transactions", credits: "balance" };
110
+ /**
111
+ * socialcrawl_request: top-level keys that are params the named endpoint
112
+ * declares (`limit`, `url`, `handle`, ...) move into params, and their names
113
+ * ride along under MOVED_PARAMS_KEY so the tool can say so.
114
+ */
115
+ function liftEndpointParams(a, known) {
116
+ if (typeof a.platform !== "string" || typeof a.resource !== "string")
117
+ return a;
118
+ const e = resolveEndpoint(a.platform, a.resource, typeof a.method === "string" ? a.method : undefined)?.endpoint;
119
+ if (!e)
120
+ return a;
121
+ const declared = new Set([...e.params.map((p) => p.name), ...e.optionalParams.map((p) => p.name), "cursor", "limit"]);
122
+ const moved = Object.keys(a).filter((k) => !known.has(k) && declared.has(k));
123
+ if (moved.length === 0)
124
+ return a;
125
+ const out = { ...a };
126
+ const params = isObj(a.params) ? { ...a.params } : {};
127
+ for (const k of moved) {
128
+ if (params[k] === undefined)
129
+ params[k] = out[k];
130
+ delete out[k];
131
+ }
132
+ params[MOVED_PARAMS_KEY] = moved.join(",");
133
+ out.params = params;
134
+ return out;
135
+ }
136
+ function hintFor(kind, key) {
137
+ if (NAMING[kind] && ENDPOINT_ALIASES.has(key))
138
+ return ENDPOINT_HINT;
139
+ return PER_TOOL[kind]?.[key] ?? ALIASES[key];
140
+ }
141
+ /** True when a call to `kind` must name an endpoint and this one does not. */
142
+ function needsEndpoint(kind, a) {
143
+ if (namedEndpoint(a) !== undefined)
144
+ return false;
145
+ if (kind === "request" || kind === "endpoint")
146
+ return true;
147
+ return kind === "collect" && a.result_id === undefined;
148
+ }
149
+ /**
150
+ * `schema` with the preprocessor in front. The result still advertises the
151
+ * object's own JSON Schema (the SDK lists `shape`, and the converter reads a
152
+ * preprocess as its inner schema), so the tool's listed schema does not grow.
153
+ */
154
+ export function withNormalizedArgs(schema, kind) {
155
+ const known = new Set(Object.keys(schema.shape));
156
+ const effects = z.preprocess((raw, ctx) => {
157
+ const n = normalizeArgs(kind, raw);
158
+ if (!isObj(n))
159
+ return n;
160
+ const a = kind === "request" ? liftEndpointParams(n, known) : n;
161
+ const unknown = Object.keys(a).filter((k) => !known.has(k));
162
+ if (unknown.length > 0) {
163
+ for (const k of unknown) {
164
+ const hint = hintFor(kind, k);
165
+ ctx.addIssue({
166
+ code: z.ZodIssueCode.custom,
167
+ path: [k],
168
+ message: `Unknown key "${k}"${hint ? `: ${hint}` : ""}. Allowed keys: ${[...known].join(", ")}.`,
169
+ fatal: true,
170
+ });
171
+ }
172
+ return z.NEVER;
173
+ }
174
+ if (needsEndpoint(kind, a)) {
175
+ ctx.addIssue({
176
+ code: z.ZodIssueCode.custom,
177
+ path: [NAMING[kind] === "id" ? "id" : "platform"],
178
+ message: `Name the endpoint: ${ENDPOINT_HINT.replace(/^use /, "")}${kind === "collect" ? "; or result_id to read a stored result" : ""}.`,
179
+ fatal: true,
180
+ });
181
+ return z.NEVER;
182
+ }
183
+ return a;
184
+ }, schema);
185
+ // The SDK lists (and validates against) an object schema when it finds `shape`.
186
+ Object.defineProperty(effects, "shape", { get: () => schema.shape });
187
+ return effects;
188
+ }
189
+ //# sourceMappingURL=normalize.js.map