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.
- package/README.md +94 -112
- package/dist/client.d.ts +2 -0
- package/dist/client.js +4 -0
- package/dist/constants.d.ts +10 -1
- package/dist/constants.js +10 -1
- package/dist/cost-guard.d.ts +8 -1
- package/dist/cost-guard.js +21 -9
- package/dist/data/docs-handwritten.js +4 -3
- package/dist/data/docs.js +1 -1
- package/dist/data/endpoints.js +65 -33
- package/dist/data/examples.js +1 -1
- package/dist/data/guide.d.ts +1 -1
- package/dist/data/guide.js +1 -1
- package/dist/data/outputs.js +218 -217
- package/dist/data/platforms.js +1 -1
- package/dist/data/recipes.js +1 -1
- package/dist/data/registry-meta.d.ts +4 -4
- package/dist/data/registry-meta.js +4 -4
- package/dist/endpoint-resolve.d.ts +10 -0
- package/dist/endpoint-resolve.js +34 -0
- package/dist/format/shape.d.ts +6 -0
- package/dist/format/shape.js +64 -0
- package/dist/freshness.d.ts +27 -4
- package/dist/freshness.js +42 -19
- package/dist/oauth/jwt-verifier.js +7 -0
- package/dist/oauth/resource-server.d.ts +3 -1
- package/dist/oauth/resource-server.js +12 -2
- package/dist/oauth/scopes.d.ts +13 -0
- package/dist/oauth/scopes.js +33 -0
- package/dist/result.d.ts +2 -0
- package/dist/result.js +8 -0
- package/dist/schemas/normalize.d.ts +27 -0
- package/dist/schemas/normalize.js +189 -0
- package/dist/schemas/outputs.d.ts +51 -31
- package/dist/schemas/outputs.js +10 -4
- package/dist/schemas/tools.d.ts +43 -8
- package/dist/schemas/tools.js +20 -7
- package/dist/server.js +17 -12
- package/dist/tools/cohorts.d.ts +3 -1
- package/dist/tools/cohorts.js +11 -10
- package/dist/tools/collect.d.ts +7 -3
- package/dist/tools/collect.js +110 -9
- package/dist/tools/discover.js +22 -27
- package/dist/tools/endpoint.js +9 -5
- package/dist/tools/estimate.js +53 -9
- package/dist/tools/find.d.ts +4 -0
- package/dist/tools/find.js +276 -9
- package/dist/tools/manage.d.ts +4 -0
- package/dist/tools/manage.js +106 -4
- package/dist/tools/monitors.d.ts +8 -1
- package/dist/tools/monitors.js +17 -12
- package/dist/tools/pricing.d.ts +1 -5
- package/dist/tools/pricing.js +17 -0
- package/dist/tools/request.d.ts +2 -11
- package/dist/tools/request.js +123 -74
- package/dist/tools/web.d.ts +3 -1
- package/dist/tools/web.js +4 -3
- package/dist/types.d.ts +9 -4
- package/package.json +2 -2
package/dist/tools/monitors.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { apiRequest } from "../client.js";
|
|
1
|
+
import { apiRequest, withDryRun } from "../client.js";
|
|
2
2
|
import { findEndpoint } from "../data/endpoints.js";
|
|
3
3
|
const ID_ACTIONS = new Set([
|
|
4
4
|
"get",
|
|
@@ -31,7 +31,8 @@ function pruneQuery(q) {
|
|
|
31
31
|
}
|
|
32
32
|
return out;
|
|
33
33
|
}
|
|
34
|
-
export async function monitors(ctx, input) {
|
|
34
|
+
export async function monitors(ctx, input, opts = {}) {
|
|
35
|
+
const send = (o) => apiRequest(ctx, withDryRun(o, opts.dryRun));
|
|
35
36
|
const { action } = input;
|
|
36
37
|
if (ID_ACTIONS.has(action) && !input.id) {
|
|
37
38
|
return `Error: The "${action}" action requires a monitor \`id\`. List your monitors with action "list" to find it.`;
|
|
@@ -50,8 +51,9 @@ export async function monitors(ctx, input) {
|
|
|
50
51
|
missing.push("`recipe` (e.g., \"prism/brand-mentions\" or \"tiktok/profile\")");
|
|
51
52
|
if (!input.cadence)
|
|
52
53
|
missing.push("`cadence` (\"hourly\" | \"daily\" | \"weekly\" | a cron expression)");
|
|
53
|
-
|
|
54
|
-
|
|
54
|
+
// A tracking monitor can be download-only; any other needs somewhere to deliver.
|
|
55
|
+
if (!input.webhook_url && !input.track)
|
|
56
|
+
missing.push("`webhook_url` (or `track` for a download-only tracking monitor)");
|
|
55
57
|
if (missing.length > 0) {
|
|
56
58
|
return `Error: Missing required parameter(s) for create: ${missing.join(", ")}.`;
|
|
57
59
|
}
|
|
@@ -67,8 +69,11 @@ export async function monitors(ctx, input) {
|
|
|
67
69
|
const body = {
|
|
68
70
|
recipe: input.recipe,
|
|
69
71
|
cadence: toCadence(input.cadence),
|
|
70
|
-
webhook_url: input.webhook_url,
|
|
71
72
|
};
|
|
73
|
+
if (input.webhook_url)
|
|
74
|
+
body.webhook_url = input.webhook_url;
|
|
75
|
+
if (input.track)
|
|
76
|
+
body.track = input.track;
|
|
72
77
|
if (input.params)
|
|
73
78
|
body.params = input.params;
|
|
74
79
|
if (input.name)
|
|
@@ -82,7 +87,7 @@ export async function monitors(ctx, input) {
|
|
|
82
87
|
body.output_schema = input.output_schema;
|
|
83
88
|
if (input.webhook_secret)
|
|
84
89
|
body.webhook_secret = input.webhook_secret;
|
|
85
|
-
response = await
|
|
90
|
+
response = await send({ method: "POST", path: "/v1/monitors", body });
|
|
86
91
|
label = "POST /v1/monitors";
|
|
87
92
|
break;
|
|
88
93
|
}
|
|
@@ -92,12 +97,12 @@ export async function monitors(ctx, input) {
|
|
|
92
97
|
cursor: input.cursor,
|
|
93
98
|
limit: input.limit?.toString(),
|
|
94
99
|
});
|
|
95
|
-
response = await
|
|
100
|
+
response = await send({ method: "GET", path: "/v1/monitors", query });
|
|
96
101
|
label = "GET /v1/monitors";
|
|
97
102
|
break;
|
|
98
103
|
}
|
|
99
104
|
case "get": {
|
|
100
|
-
response = await
|
|
105
|
+
response = await send({ method: "GET", path: `/v1/monitors/${id}` });
|
|
101
106
|
label = `GET /v1/monitors/${input.id}`;
|
|
102
107
|
break;
|
|
103
108
|
}
|
|
@@ -110,20 +115,20 @@ export async function monitors(ctx, input) {
|
|
|
110
115
|
limit: input.limit?.toString(),
|
|
111
116
|
include: input.include,
|
|
112
117
|
});
|
|
113
|
-
response = await
|
|
118
|
+
response = await send({ method: "GET", path: `/v1/monitors/${id}/runs`, query });
|
|
114
119
|
label = `GET /v1/monitors/${input.id}/runs`;
|
|
115
120
|
break;
|
|
116
121
|
}
|
|
117
122
|
case "timeseries": {
|
|
118
123
|
const query = pruneQuery({ metric: input.metric, from: input.from, to: input.to });
|
|
119
|
-
response = await
|
|
124
|
+
response = await send({ method: "GET", path: `/v1/monitors/${id}/timeseries`, query });
|
|
120
125
|
label = `GET /v1/monitors/${input.id}/timeseries`;
|
|
121
126
|
break;
|
|
122
127
|
}
|
|
123
128
|
case "pause":
|
|
124
129
|
case "resume": {
|
|
125
130
|
const status = action === "pause" ? "paused" : "active";
|
|
126
|
-
response = await
|
|
131
|
+
response = await send({
|
|
127
132
|
method: "PATCH",
|
|
128
133
|
path: `/v1/monitors/${id}`,
|
|
129
134
|
body: { status },
|
|
@@ -132,7 +137,7 @@ export async function monitors(ctx, input) {
|
|
|
132
137
|
break;
|
|
133
138
|
}
|
|
134
139
|
case "delete": {
|
|
135
|
-
response = await
|
|
140
|
+
response = await send({ method: "DELETE", path: `/v1/monitors/${id}` });
|
|
136
141
|
label = `DELETE /v1/monitors/${input.id}`;
|
|
137
142
|
break;
|
|
138
143
|
}
|
package/dist/tools/pricing.d.ts
CHANGED
|
@@ -32,9 +32,5 @@ export interface PricingParams {
|
|
|
32
32
|
calls?: number;
|
|
33
33
|
}
|
|
34
34
|
export declare function pricing(params: PricingParams): string;
|
|
35
|
-
|
|
36
|
-
* Text plus the `structuredContent` object. `action: "endpoint"` carries the
|
|
37
|
-
* per-call quote as numbers (the band and its worst case); the catalogue
|
|
38
|
-
* actions are prose tables, so they report `ok` and the action only.
|
|
39
|
-
*/
|
|
35
|
+
export declare function v2Wording(text: string): string;
|
|
40
36
|
export declare function pricingStructured(params: PricingParams): ToolOutput;
|
package/dist/tools/pricing.js
CHANGED
|
@@ -494,6 +494,23 @@ export function pricing(params) {
|
|
|
494
494
|
* per-call quote as numbers (the band and its worst case); the catalogue
|
|
495
495
|
* actions are prose tables, so they report `ok` and the action only.
|
|
496
496
|
*/
|
|
497
|
+
/**
|
|
498
|
+
* The 1.x pricing tool's text, worded for the 2.0 tools that reuse it
|
|
499
|
+
* (`socialcrawl_estimate`): each `action: "..."` pointer becomes the 2.0 call
|
|
500
|
+
* that gives the same answer.
|
|
501
|
+
*/
|
|
502
|
+
const V2_WORDING = [
|
|
503
|
+
[/`action: \\?"endpoint\\?"` with a platform \+ resource/g, '`socialcrawl_estimate` with `id: "platform/resource"`'],
|
|
504
|
+
[/`action: \\?"endpoint\\?"` with `platform`, `resource`(,)? and/g, '`socialcrawl_estimate` with `id: "platform/resource"` and'],
|
|
505
|
+
[/use `action: \\?"endpoint\\?"` with/g, "use `socialcrawl_estimate` with"],
|
|
506
|
+
[/`action: \\?"platform\\?"`/g, "`socialcrawl_estimate` with a platform slug as `id`"],
|
|
507
|
+
[/, or `action: \\?"list\\?"` with `maxCost` \/ `model` \/ `sort` to rank endpoints by price/g, ""],
|
|
508
|
+
[/`action: \\?"overview\\?"`/g, "`socialcrawl_estimate` with no `id`"],
|
|
509
|
+
[/`action: \\?"(judgments|hydration)\\?"`/g, '`socialcrawl_endpoint` with `id: "$1"`'],
|
|
510
|
+
];
|
|
511
|
+
export function v2Wording(text) {
|
|
512
|
+
return V2_WORDING.reduce((t, [re, to]) => t.replace(re, to), text);
|
|
513
|
+
}
|
|
497
514
|
export function pricingStructured(params) {
|
|
498
515
|
const text = pricing(params);
|
|
499
516
|
if (isErrorText(text))
|
package/dist/tools/request.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { ProgressTick } from "../client.js";
|
|
2
2
|
import type { ApiContext } from "../context.js";
|
|
3
|
-
import type { Endpoint } from "../types.js";
|
|
4
3
|
import type { ToolOutput } from "../result.js";
|
|
4
|
+
import { resolveEndpoint } from "../endpoint-resolve.js";
|
|
5
5
|
interface RequestParams {
|
|
6
6
|
platform: string;
|
|
7
7
|
resource: string;
|
|
@@ -38,15 +38,7 @@ type ParamScalar = string | number | boolean;
|
|
|
38
38
|
type ParamValue = ParamScalar | ParamScalar[];
|
|
39
39
|
/** Query values travel as strings; arrays become CSV (`label=a,b`). */
|
|
40
40
|
export declare function stringifyParams(params: Record<string, ParamValue> | undefined): Record<string, string>;
|
|
41
|
-
|
|
42
|
-
* Resolve a resource to its registered endpoint, accepting both the template
|
|
43
|
-
* (`jobs/{job_id}` with `job_id` in params) and a concrete path
|
|
44
|
-
* (`jobs/job_abc123`). Returns the path-param values a concrete path carried.
|
|
45
|
-
*/
|
|
46
|
-
export declare function resolveEndpoint(platform: string, resource: string, method: string | undefined): {
|
|
47
|
-
endpoint: Endpoint;
|
|
48
|
-
pathValues: Record<string, string>;
|
|
49
|
-
} | undefined;
|
|
41
|
+
export { resolveEndpoint };
|
|
50
42
|
export declare function request(ctx: ApiContext, input: RequestParams): Promise<string>;
|
|
51
43
|
/** Text for older clients plus the `structuredContent` object (success or error shape). */
|
|
52
44
|
export declare function requestStructured(ctx: ApiContext, input: RequestParams): Promise<ToolOutput>;
|
|
@@ -55,4 +47,3 @@ export declare function requestPage(ctx: ApiContext, input: RequestParams, opts?
|
|
|
55
47
|
output: ToolOutput;
|
|
56
48
|
envelope?: Record<string, unknown>;
|
|
57
49
|
}>;
|
|
58
|
-
export {};
|
package/dist/tools/request.js
CHANGED
|
@@ -1,19 +1,21 @@
|
|
|
1
1
|
import { findPlatform } from "../data/platforms.js";
|
|
2
|
-
import {
|
|
2
|
+
import { findEndpoint, getEndpointsByPlatform } from "../data/endpoints.js";
|
|
3
3
|
import { makeRequest, apiRequest } from "../client.js";
|
|
4
4
|
import { timeoutSecondsFor, wantsStream } from "../timeouts.js";
|
|
5
5
|
import { pollLine, requestJobHandle } from "../jobs.js";
|
|
6
6
|
import { formatCost, worstCaseCost } from "../pricing.js";
|
|
7
7
|
import { quoteHydration } from "../hydration.js";
|
|
8
8
|
import { quoteJudgments } from "../judgments.js";
|
|
9
|
-
import { errorFromText, structureEnvelope, summaryLine } from "../result.js";
|
|
10
|
-
import { RESULT_CHAR_BUDGET } from "../constants.js";
|
|
9
|
+
import { errorFromText, shortCursor, structureEnvelope, summaryLine } from "../result.js";
|
|
10
|
+
import { INLINE_MAX_BYTES, INLINE_MAX_ROWS, MOVED_PARAMS_KEY, RESULT_CHAR_BUDGET } from "../constants.js";
|
|
11
11
|
import { shapeEnvelope } from "../format/shape.js";
|
|
12
|
+
import { outputsFor } from "../data/outputs.js";
|
|
12
13
|
import { resultsStore, resultUri, scopeOf } from "../results-store.js";
|
|
13
14
|
import { randomUUID } from "node:crypto";
|
|
14
15
|
import { checkGuard, quoteCall } from "../cost-guard.js";
|
|
15
16
|
import { recordSpend } from "../session-spend.js";
|
|
16
17
|
import { suggestEndpoints, suggestPlatforms } from "../search/catalog.js";
|
|
18
|
+
import { resolveEndpoint } from "../endpoint-resolve.js";
|
|
17
19
|
/** Query values travel as strings; arrays become CSV (`label=a,b`). */
|
|
18
20
|
export function stringifyParams(params) {
|
|
19
21
|
const out = {};
|
|
@@ -22,38 +24,7 @@ export function stringifyParams(params) {
|
|
|
22
24
|
}
|
|
23
25
|
return out;
|
|
24
26
|
}
|
|
25
|
-
|
|
26
|
-
* Resolve a resource to its registered endpoint, accepting both the template
|
|
27
|
-
* (`jobs/{job_id}` with `job_id` in params) and a concrete path
|
|
28
|
-
* (`jobs/job_abc123`). Returns the path-param values a concrete path carried.
|
|
29
|
-
*/
|
|
30
|
-
export function resolveEndpoint(platform, resource, method) {
|
|
31
|
-
const direct = findEndpoint(platform, resource, method);
|
|
32
|
-
if (direct)
|
|
33
|
-
return { endpoint: direct, pathValues: {} };
|
|
34
|
-
const parts = resource.split("/");
|
|
35
|
-
for (const e of ENDPOINTS) {
|
|
36
|
-
if (e.platform !== platform || !e.resource.includes("{"))
|
|
37
|
-
continue;
|
|
38
|
-
if (method && e.method !== method)
|
|
39
|
-
continue;
|
|
40
|
-
const tpl = e.resource.split("/");
|
|
41
|
-
if (tpl.length !== parts.length)
|
|
42
|
-
continue;
|
|
43
|
-
const values = {};
|
|
44
|
-
const ok = tpl.every((seg, i) => {
|
|
45
|
-
const m = /^\{(\w+)\}$/.exec(seg);
|
|
46
|
-
if (m) {
|
|
47
|
-
values[m[1]] = decodeURIComponent(parts[i]);
|
|
48
|
-
return parts[i].length > 0;
|
|
49
|
-
}
|
|
50
|
-
return seg === parts[i];
|
|
51
|
-
});
|
|
52
|
-
if (ok)
|
|
53
|
-
return { endpoint: e, pathValues: values };
|
|
54
|
-
}
|
|
55
|
-
return undefined;
|
|
56
|
-
}
|
|
27
|
+
export { resolveEndpoint };
|
|
57
28
|
/** `jobs/{job_id}` + `{ job_id: "abc" }` → `jobs/abc`. */
|
|
58
29
|
function fillPath(resource, values) {
|
|
59
30
|
return resource.replace(/\{(\w+)\}/g, (_, name) => encodeURIComponent(String(values[name] ?? `{${name}}`)));
|
|
@@ -161,6 +132,23 @@ function unknownParams(endpoint, provided) {
|
|
|
161
132
|
]);
|
|
162
133
|
return Object.keys(provided).filter((name) => !known.has(name));
|
|
163
134
|
}
|
|
135
|
+
/**
|
|
136
|
+
* The envelope for the text, with any long `next_cursor` cut to its head and
|
|
137
|
+
* "…" (a cursor can run to kilobytes). structuredContent keeps the full value.
|
|
138
|
+
*/
|
|
139
|
+
function clipCursors(env) {
|
|
140
|
+
const clip = (p) => p && typeof p === "object" && typeof p.next_cursor === "string"
|
|
141
|
+
? { ...p, next_cursor: shortCursor(p.next_cursor) }
|
|
142
|
+
: p;
|
|
143
|
+
const out = { ...env };
|
|
144
|
+
if (out.pagination)
|
|
145
|
+
out.pagination = clip(out.pagination);
|
|
146
|
+
const d = out.data;
|
|
147
|
+
if (d && typeof d === "object" && !Array.isArray(d) && d.pagination) {
|
|
148
|
+
out.data = { ...d, pagination: clip(d.pagination) };
|
|
149
|
+
}
|
|
150
|
+
return out;
|
|
151
|
+
}
|
|
164
152
|
export async function request(ctx, input) {
|
|
165
153
|
return (await requestStructured(ctx, input)).text;
|
|
166
154
|
}
|
|
@@ -218,11 +206,39 @@ async function runRequest(ctx, input, captured, opts) {
|
|
|
218
206
|
].join(" ");
|
|
219
207
|
}
|
|
220
208
|
const isPost = endpoint.method === "POST";
|
|
209
|
+
const notices = [];
|
|
210
|
+
let inParams = input.params;
|
|
211
|
+
const lifted = inParams?.[MOVED_PARAMS_KEY];
|
|
212
|
+
if (inParams && lifted !== undefined) {
|
|
213
|
+
const { [MOVED_PARAMS_KEY]: _marker, ...restParams } = inParams;
|
|
214
|
+
inParams = restParams;
|
|
215
|
+
const names = String(lifted).split(",").map((n) => `\`${n}\``).join(", ");
|
|
216
|
+
notices.push(`Moved top-level ${names} into params: ${names} ${String(lifted).includes(",") ? "are" : "is a"} ${input.platform}/${endpoint.resource} param${String(lifted).includes(",") ? "s" : ""}. Put endpoint params in params next time.`);
|
|
217
|
+
}
|
|
218
|
+
let inBody = input.body;
|
|
219
|
+
// A POST endpoint takes its fields in the JSON body: params given without a
|
|
220
|
+
// body move there (path and query-only params stay), arrays intact.
|
|
221
|
+
if (isPost && inParams && Object.keys(inParams).length > 0 && (!inBody || Object.keys(inBody).length === 0)) {
|
|
222
|
+
const pathOnly = pathParamNames(endpoint.resource);
|
|
223
|
+
const keep = {};
|
|
224
|
+
const move = {};
|
|
225
|
+
for (const [k, v] of Object.entries(inParams)) {
|
|
226
|
+
if (pathOnly.has(k) || isQueryParam(endpoint, k))
|
|
227
|
+
keep[k] = v;
|
|
228
|
+
else
|
|
229
|
+
move[k] = v;
|
|
230
|
+
}
|
|
231
|
+
if (Object.keys(move).length > 0) {
|
|
232
|
+
inParams = keep;
|
|
233
|
+
inBody = move;
|
|
234
|
+
notices.push(`Moved ${Object.keys(move).map((k) => `\`${k}\``).join(", ")} from params to body: ${input.platform}/${endpoint.resource} is a POST endpoint and reads them from the JSON body.`);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
221
237
|
const providedParams = {
|
|
222
238
|
...resolved.pathValues,
|
|
223
|
-
...stringifyParams(
|
|
239
|
+
...stringifyParams(inParams),
|
|
224
240
|
};
|
|
225
|
-
const providedBody =
|
|
241
|
+
const providedBody = inBody ?? {};
|
|
226
242
|
// A required param may arrive via `params` or `body`; POST batch params
|
|
227
243
|
// (ids/urls/items) conventionally live in `body`.
|
|
228
244
|
const merged = { ...providedParams, ...providedBody };
|
|
@@ -253,12 +269,52 @@ async function runRequest(ctx, input, captured, opts) {
|
|
|
253
269
|
`Use socialcrawl_endpoint with id "${input.platform}/${endpoint.resource}" for the full parameter contract. No credits were charged.`,
|
|
254
270
|
].join("\n");
|
|
255
271
|
}
|
|
272
|
+
const pathNames = pathParamNames(endpoint.resource);
|
|
273
|
+
// POST batch endpoint — split provided values into a JSON body and a query
|
|
274
|
+
// string, routing `in: "query"` params (e.g. YouTube `hl`) to the query and
|
|
275
|
+
// everything else to the body. Built here so the quote prices what is sent.
|
|
276
|
+
const postQuery = {};
|
|
277
|
+
const postBody = {};
|
|
278
|
+
if (isPost) {
|
|
279
|
+
for (const [k, v] of Object.entries(providedParams)) {
|
|
280
|
+
if (pathNames.has(k))
|
|
281
|
+
continue;
|
|
282
|
+
if (isQueryParam(endpoint, k))
|
|
283
|
+
postQuery[k] = v;
|
|
284
|
+
else
|
|
285
|
+
postBody[k] = coerceJson(v);
|
|
286
|
+
}
|
|
287
|
+
for (const [k, v] of Object.entries(providedBody)) {
|
|
288
|
+
if (pathNames.has(k))
|
|
289
|
+
continue;
|
|
290
|
+
if (isQueryParam(endpoint, k))
|
|
291
|
+
postQuery[k] = String(v);
|
|
292
|
+
else
|
|
293
|
+
postBody[k] = coerceJson(v);
|
|
294
|
+
}
|
|
295
|
+
if (input.fields)
|
|
296
|
+
postQuery.fields = input.fields;
|
|
297
|
+
}
|
|
256
298
|
// What to count as spent when a success does not say (the quoted hold).
|
|
257
299
|
let holdCharge = opts.hold;
|
|
258
|
-
//
|
|
300
|
+
// The API's quote for this exact call, when it was asked.
|
|
301
|
+
let exactHold;
|
|
302
|
+
// Cost guard: quote the exact call, refuse over max_credits, ask above the threshold.
|
|
259
303
|
if (!opts.skipGuard) {
|
|
260
|
-
const
|
|
304
|
+
const exact = isPost ? { params: postQuery, body: postBody } : undefined;
|
|
305
|
+
const quote = await quoteCall(ctx, endpoint, merged, input.max_credits, exact);
|
|
306
|
+
if (quote.rejection) {
|
|
307
|
+
return [
|
|
308
|
+
"Error: Invalid parameter value(s) — the API would reject this with a 400 before billing:",
|
|
309
|
+
`- ${quote.rejection}`,
|
|
310
|
+
...notices.map((n) => `- ${n}`),
|
|
311
|
+
"",
|
|
312
|
+
`Use socialcrawl_endpoint with id "${input.platform}/${endpoint.resource}" for the full parameter contract. No credits were charged.`,
|
|
313
|
+
].join("\n");
|
|
314
|
+
}
|
|
261
315
|
holdCharge = quote.hold;
|
|
316
|
+
if (quote.source === "estimate")
|
|
317
|
+
exactHold = quote.hold;
|
|
262
318
|
const stop = await checkGuard(ctx, {
|
|
263
319
|
hold: quote.hold,
|
|
264
320
|
exposure: quote.hold,
|
|
@@ -279,7 +335,6 @@ async function runRequest(ctx, input, captured, opts) {
|
|
|
279
335
|
onProgress: input.onProgress,
|
|
280
336
|
meta: callMeta,
|
|
281
337
|
};
|
|
282
|
-
const pathNames = pathParamNames(endpoint.resource);
|
|
283
338
|
const resourcePath = fillPath(endpoint.resource, merged);
|
|
284
339
|
if (!isPost) {
|
|
285
340
|
// GET (and the rare non-POST) — everything is a query param, except the
|
|
@@ -301,35 +356,12 @@ async function runRequest(ctx, input, captured, opts) {
|
|
|
301
356
|
});
|
|
302
357
|
}
|
|
303
358
|
else {
|
|
304
|
-
// POST batch endpoint — split provided values into a JSON body and a
|
|
305
|
-
// query string, routing `in: "query"` params (e.g. YouTube `hl`) to the
|
|
306
|
-
// query and everything else to the body.
|
|
307
|
-
const query = {};
|
|
308
|
-
const bodyOut = {};
|
|
309
|
-
for (const [k, v] of Object.entries(providedParams)) {
|
|
310
|
-
if (pathNames.has(k))
|
|
311
|
-
continue;
|
|
312
|
-
if (isQueryParam(endpoint, k))
|
|
313
|
-
query[k] = v;
|
|
314
|
-
else
|
|
315
|
-
bodyOut[k] = coerceJson(v);
|
|
316
|
-
}
|
|
317
|
-
for (const [k, v] of Object.entries(providedBody)) {
|
|
318
|
-
if (pathNames.has(k))
|
|
319
|
-
continue;
|
|
320
|
-
if (isQueryParam(endpoint, k))
|
|
321
|
-
query[k] = String(v);
|
|
322
|
-
else
|
|
323
|
-
bodyOut[k] = coerceJson(v);
|
|
324
|
-
}
|
|
325
|
-
if (input.fields)
|
|
326
|
-
query.fields = input.fields;
|
|
327
359
|
response = await apiRequest(ctx, {
|
|
328
360
|
raw: true,
|
|
329
361
|
method: "POST",
|
|
330
362
|
path: `/v1/${input.platform}/${resourcePath}`,
|
|
331
|
-
query,
|
|
332
|
-
body:
|
|
363
|
+
query: postQuery,
|
|
364
|
+
body: postBody,
|
|
333
365
|
idempotencyKey: input.idempotencyKey,
|
|
334
366
|
errorPlatform: input.platform,
|
|
335
367
|
...longCall,
|
|
@@ -418,23 +450,36 @@ async function runRequest(ctx, input, captured, opts) {
|
|
|
418
450
|
}
|
|
419
451
|
headerLines.push(`**Paging:** pass \`cursor\` from \`pagination.next_cursor\` for the next page; stop when \`pagination.has_more\` is false. Each page is billed separately.${extras.length > 0 ? ` Also: ${extras.join("; ")}.` : ""}`);
|
|
420
452
|
}
|
|
453
|
+
if (exactHold !== undefined)
|
|
454
|
+
headerLines.push(`**Quote:** this exact call holds ${exactHold}cr (the API's estimate).`);
|
|
455
|
+
for (const n of notices)
|
|
456
|
+
headerLines.push(`**Note:** ${n}`);
|
|
421
457
|
const header = `${headerLines.join("\n")}\n\n`;
|
|
422
458
|
if (/^Error(?::| \(\d+\):)/.test(response)) {
|
|
423
459
|
return `${header}${response}`;
|
|
424
460
|
}
|
|
425
|
-
const quotedMax = worstCaseCost(endpoint.pricing);
|
|
461
|
+
const quotedMax = exactHold ?? worstCaseCost(endpoint.pricing);
|
|
426
462
|
const endpointName = `${input.platform}/${endpoint.resource}`;
|
|
427
463
|
try {
|
|
428
464
|
const parsed = JSON.parse(response);
|
|
429
465
|
// Cut only at row boundaries so the result is always valid JSON; the full
|
|
430
466
|
// body goes to the results store behind a resource link.
|
|
431
467
|
const format = input.format ?? "json";
|
|
432
|
-
|
|
468
|
+
// A small page comes back whole (INLINE_MAX_ROWS rows, INLINE_MAX_BYTES); a larger one is cut to the budget.
|
|
469
|
+
// The rows get room on top of the usual budget; the rest of the page does not.
|
|
470
|
+
const pageRows = structureEnvelope(parsed).rows;
|
|
471
|
+
const rowBytes = Array.isArray(pageRows) ? JSON.stringify(pageRows).length : 0;
|
|
472
|
+
const small = Array.isArray(pageRows) && pageRows.length <= INLINE_MAX_ROWS && response.length <= INLINE_MAX_BYTES;
|
|
473
|
+
// A single-object endpoint's main object, from the contract (`rows_at: data.quote` -> quote).
|
|
474
|
+
const mainKey = /^data\.([A-Za-z0-9_]+)$/.exec(outputsFor(endpoint)?.rows_at ?? "")?.[1];
|
|
475
|
+
const smallObject = !Array.isArray(pageRows) && mainKey !== undefined && response.length <= INLINE_MAX_BYTES;
|
|
476
|
+
const budget = (smallObject ? INLINE_MAX_BYTES : RESULT_CHAR_BUDGET + (small ? rowBytes : 0)) - header.length - 1500;
|
|
433
477
|
const shaped = shapeEnvelope(parsed, {
|
|
434
478
|
fields: input.fields,
|
|
435
479
|
maxItems: input.max_items,
|
|
436
480
|
format,
|
|
437
481
|
budget,
|
|
482
|
+
mainKey,
|
|
438
483
|
});
|
|
439
484
|
const structured = {
|
|
440
485
|
ok: true,
|
|
@@ -450,6 +495,8 @@ async function runRequest(ctx, input, captured, opts) {
|
|
|
450
495
|
structured.credits = credits;
|
|
451
496
|
captured.envelope = parsed;
|
|
452
497
|
const notes = [];
|
|
498
|
+
if (notices.length > 0)
|
|
499
|
+
structured.warnings = [...(structured.warnings ?? []), ...notices];
|
|
453
500
|
if (shaped.warnings && shaped.warnings.length > 0) {
|
|
454
501
|
structured.warnings = [...(structured.warnings ?? []), ...shaped.warnings];
|
|
455
502
|
notes.push(...shaped.warnings);
|
|
@@ -458,8 +505,10 @@ async function runRequest(ctx, input, captured, opts) {
|
|
|
458
505
|
let uri;
|
|
459
506
|
if (linkWorthy) {
|
|
460
507
|
const id = typeof parsed.request_id === "string" && parsed.request_id ? parsed.request_id : randomUUID();
|
|
461
|
-
if (resultsStore.put(scopeOf(ctx.apiKey), id, response))
|
|
508
|
+
if (resultsStore.put(scopeOf(ctx.apiKey), id, response)) {
|
|
462
509
|
uri = resultUri(id);
|
|
510
|
+
structured.result_id = id;
|
|
511
|
+
}
|
|
463
512
|
else
|
|
464
513
|
notes.push(`full body (${Buffer.byteLength(response).toLocaleString()} bytes) is too large to store; narrow the request (limit, fields) instead`);
|
|
465
514
|
}
|
|
@@ -469,17 +518,17 @@ async function runRequest(ctx, input, captured, opts) {
|
|
|
469
518
|
trunc.shown = shaped.shown;
|
|
470
519
|
trunc.total = shaped.total;
|
|
471
520
|
notes.push(shaped.shown
|
|
472
|
-
? `rows 1–${shaped.shown} of ${shaped.total} shown; full page stored as resource ${uri}`
|
|
473
|
-
: `no row fit; ${shaped.total} rows stored as resource ${uri}`);
|
|
521
|
+
? `rows 1–${shaped.shown} of ${shaped.total} shown; full page stored as resource ${uri} (read the rest in this session with result_id "${String(structured.result_id)}": socialcrawl_collect { result_id, offset: ${shaped.shown} })`
|
|
522
|
+
: `no row fit; ${shaped.total} rows stored as resource ${uri} (read them in this session with result_id "${String(structured.result_id)}": socialcrawl_collect { result_id })`);
|
|
474
523
|
}
|
|
475
524
|
else {
|
|
476
525
|
trunc.omitted_keys = shaped.omittedKeys;
|
|
477
|
-
notes.push(`${shaped.omittedKeys?.length ?? 0} large field(s) omitted (${(shaped.omittedKeys ?? []).join(", ")}); full body stored as resource ${uri}`);
|
|
526
|
+
notes.push(`${shaped.omittedKeys?.length ?? 0} large field(s) omitted (${(shaped.omittedKeys ?? []).join(", ")}); full body stored as resource ${uri} (read it in this session with result_id "${String(structured.result_id)}": socialcrawl_collect { result_id })`);
|
|
478
527
|
}
|
|
479
528
|
structured.truncated = trunc;
|
|
480
529
|
}
|
|
481
530
|
else if (uri) {
|
|
482
|
-
notes.push(`full body stored as resource ${uri}`);
|
|
531
|
+
notes.push(`full body stored as resource ${uri} (read it in this session with result_id "${String(structured.result_id)}": socialcrawl_collect { result_id })`);
|
|
483
532
|
}
|
|
484
533
|
// The table lives once, in the text; structuredContent carries only its row count
|
|
485
534
|
// (a client reading both would otherwise pay for the CSV twice).
|
|
@@ -529,10 +578,10 @@ async function runRequest(ctx, input, captured, opts) {
|
|
|
529
578
|
const { items: _items, ...restData } = d;
|
|
530
579
|
env.data = restData;
|
|
531
580
|
}
|
|
532
|
-
payload = `\`\`\`json\n${JSON.stringify({ ...env, summary: shaped.summary })}\n\`\`\``;
|
|
581
|
+
payload = `\`\`\`json\n${JSON.stringify(clipCursors({ ...env, summary: shaped.summary }))}\n\`\`\``;
|
|
533
582
|
}
|
|
534
583
|
else
|
|
535
|
-
payload = `\`\`\`json\n${JSON.stringify(shaped.envelope)}\n\`\`\``;
|
|
584
|
+
payload = `\`\`\`json\n${JSON.stringify(clipCursors(shaped.envelope))}\n\`\`\``;
|
|
536
585
|
return `${header}**Result:** ${line}${noteBlock}\n\n${payload}`;
|
|
537
586
|
}
|
|
538
587
|
catch {
|
package/dist/tools/web.d.ts
CHANGED
|
@@ -23,7 +23,9 @@ export interface WebParams {
|
|
|
23
23
|
input?: Record<string, unknown>;
|
|
24
24
|
idempotencyKey?: string;
|
|
25
25
|
}
|
|
26
|
-
export declare function web(ctx: ApiContext, params: WebParams
|
|
26
|
+
export declare function web(ctx: ApiContext, params: WebParams, opts?: {
|
|
27
|
+
dryRun?: boolean;
|
|
28
|
+
}): Promise<string>;
|
|
27
29
|
/**
|
|
28
30
|
* The (method, resource) pair each action targets. Exported so the coverage
|
|
29
31
|
* test can assert that every web endpoint has an action and every action
|
package/dist/tools/web.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { apiRequest } from "../client.js";
|
|
1
|
+
import { apiRequest, withDryRun } from "../client.js";
|
|
2
2
|
import { timeoutSecondsFor } from "../timeouts.js";
|
|
3
3
|
import { pollLine, webJobHandle } from "../jobs.js";
|
|
4
4
|
import { findEndpoint } from "../data/endpoints.js";
|
|
@@ -48,7 +48,8 @@ function toQuery(input) {
|
|
|
48
48
|
}
|
|
49
49
|
return out;
|
|
50
50
|
}
|
|
51
|
-
export async function web(ctx, params) {
|
|
51
|
+
export async function web(ctx, params, opts = {}) {
|
|
52
|
+
const send = (o) => apiRequest(ctx, withDryRun(o, opts.dryRun));
|
|
52
53
|
const spec = ACTIONS[params.action];
|
|
53
54
|
if (!spec) {
|
|
54
55
|
return `Error: Unknown action "${String(params.action)}". Valid actions: ${Object.keys(ACTIONS).join(", ")}.`;
|
|
@@ -72,7 +73,7 @@ export async function web(ctx, params) {
|
|
|
72
73
|
const isBodyMethod = spec.method === "POST" || spec.method === "PATCH";
|
|
73
74
|
const priced = findEndpoint("web", spec.resource, spec.method);
|
|
74
75
|
const callMeta = {};
|
|
75
|
-
const response = await
|
|
76
|
+
const response = await send({
|
|
76
77
|
timeoutMs: timeoutSecondsFor(priced) * 1000,
|
|
77
78
|
meta: callMeta,
|
|
78
79
|
method: spec.method === "PATCH" ? "PATCH" : spec.method,
|
package/dist/types.d.ts
CHANGED
|
@@ -334,16 +334,21 @@ export interface Endpoint {
|
|
|
334
334
|
/** Measured latency over recent calls, in milliseconds (dump v4), when sampled. */
|
|
335
335
|
latency_ms?: LatencyStats;
|
|
336
336
|
}
|
|
337
|
-
/**
|
|
337
|
+
/**
|
|
338
|
+
* Registry `purpose` block: one line each, generated from the same source as the skill.
|
|
339
|
+
* Every field is nullable: an endpoint can reach the dump before its copy is written,
|
|
340
|
+
* and consumers fall back to `Endpoint.summary` (or skip the line).
|
|
341
|
+
*/
|
|
338
342
|
export interface EndpointPurpose {
|
|
339
|
-
summary: string;
|
|
343
|
+
summary: string | null;
|
|
340
344
|
returns: string | null;
|
|
341
345
|
use_when: string | null;
|
|
342
346
|
not_for: string | null;
|
|
343
347
|
}
|
|
348
|
+
/** Job taxonomy; null while an endpoint is not classified yet. */
|
|
344
349
|
export interface EndpointTaxonomy {
|
|
345
|
-
purpose: string;
|
|
346
|
-
job_family: string;
|
|
350
|
+
purpose: string | null;
|
|
351
|
+
job_family: string | null;
|
|
347
352
|
takes_item_id_from_another_endpoint?: boolean;
|
|
348
353
|
}
|
|
349
354
|
export interface LatencyStats {
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "socialcrawl-mcp",
|
|
3
|
-
"version": "2.0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "2.0.2",
|
|
4
|
+
"description": "One unified API for social and web data — social media (incl. Douyin, Xiaohongshu, Telegram, Quora, Bluesky, Apple Music, Product Hunt), commerce, marketplaces & product reviews, retail (Amazon, Walmart, Target, Home Depot, eBay, Klarna, AliExpress, Etsy, Sephora, H&M, Kohl's, Wayfair, Gumtree, Google Shopping), app stores (Google Play, App Store), places, travel & local (Tripadvisor, Yelp, Google Business/Hotels), business & software reputation (Trustpilot, G2), jobs & salaries (LinkedIn, Indeed, Bing, Xing), markets & finance, US congressional trading disclosures, on-page SEO audits, web research (Tavily, Perplexity), full web scraping & browser automation (scrape, crawl, agent, monitors, sessions), audience-filtered mention search over a panel you supply (cohorts), Korean search (Naver + Data Lab), content/sentiment analysis, Google News/Trends, GitHub, Hacker News, Polymarket, AI X-search via Grok, cross-platform Prism composites, and a universal /search/everywhere meta-search — with exact per-endpoint credit pricing (ladder, flat, and metered bands), free default row judgments with metered label/relevance quotes, and itemised per-call and per-job cost quotes for every one.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
7
7
|
"bin": {
|