pagesift 1.6.1

A single-binary, Firecrawl-compatible web scraping engine that turns pages into clean Markdown.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
//! MCP `pagesift_sync` handler backed by `Engine` and `pagesift_store::Store`.

use std::collections::BTreeSet;
use std::sync::Arc;

use pagesift_api::sources::{CreateSourceRequest, build_source_spec, validate_source_id};
use pagesift_api::{ApiError, Engine};
use pagesift_mcp::{
    BoxFuture, ToolContext, ToolDef, ToolError, ToolHandler, ToolOutput, ToolResult, tools,
};
use pagesift_store::{FreshnessPolicy, MAX_DELTAS_PER_SOURCE, Store, SyncBudget};
use serde_json::{Map, Value, json};

pub(crate) struct SyncTool {
    pub(crate) engine: Arc<dyn Engine>,
    pub(crate) store: Option<Store>,
}

fn bad(e: ApiError) -> ToolError {
    ToolError::new(format!("{}: {}", e.code.as_str(), e.message))
}

fn parse_as_of_arg(args: &Map<String, Value>) -> Result<Option<u64>, ToolError> {
    let Some(v) = args.get("asOf") else {
        return Ok(None);
    };
    let Some(raw) = v.as_str() else {
        return Err(ToolError::new("asOf must be a string"));
    };
    let s = raw.trim();
    if s.is_empty() {
        return Ok(None);
    }
    if let Ok(ms) = s.parse::<u64>() {
        return Ok(Some(ms));
    }
    pagesift_graph::parse_timestamp_ms(s)
        .map(Some)
        .ok_or_else(|| ToolError::new(format!("invalid asOf timestamp {s:?}")))
}

fn string_vec(args: &Map<String, Value>, key: &str) -> Result<Vec<String>, ToolError> {
    let Some(val) = args.get(key) else {
        return Ok(Vec::new());
    };
    let Some(arr) = val.as_array() else {
        return Err(ToolError::new(format!("{key} must be an array of strings")));
    };
    let mut out = Vec::with_capacity(arr.len());
    for item in arr {
        let Some(s) = item.as_str() else {
            return Err(ToolError::new(format!("{key} entries must be strings")));
        };
        out.push(s.to_string());
    }
    Ok(out)
}

fn require_source_id(args: &Map<String, Value>) -> Result<String, ToolError> {
    let raw = args
        .get("sourceId")
        .and_then(Value::as_str)
        .ok_or_else(|| ToolError::new("sourceId is required for this action"))?;
    validate_source_id(raw).map_err(bad)
}

impl ToolHandler for SyncTool {
    fn definition(&self) -> ToolDef {
        tools::sync_def()
    }

    fn call(&self, args: Map<String, Value>, _ctx: ToolContext) -> BoxFuture<'_, ToolResult> {
        Box::pin(async move {
            let allowed: BTreeSet<&str> = [
                "action",
                "sourceId",
                "name",
                "seeds",
                "includePaths",
                "excludePaths",
                "maxDepth",
                "allowSubdomains",
                "requiredFields",
                "allowBrowser",
                "maxRequestsPerTick",
                "targetItems",
                "forceAll",
                "maxRequests",
                "asOf",
                "tickId",
                "limit",
            ]
            .into_iter()
            .collect();
            for k in args.keys() {
                if !allowed.contains(k.as_str()) {
                    return Err(ToolError::new(format!("unknown argument `{k}`")));
                }
            }

            let action = args
                .get("action")
                .and_then(Value::as_str)
                .map(str::trim)
                .filter(|s| !s.is_empty())
                .ok_or_else(|| ToolError::new("action is required"))?
                .to_string();

            let store = self.store.clone().ok_or_else(|| {
                ToolError::new("pagesift_sync requires persistent storage enabled on the server")
            })?;

            match action.as_str() {
                "create" => {
                    let seeds = string_vec(&args, "seeds")?;
                    let mut budget = SyncBudget::default();
                    if let Some(n) = args.get("maxRequestsPerTick").and_then(Value::as_u64) {
                        let parsed = usize::try_from(n)
                            .map_err(|_| ToolError::new("maxRequestsPerTick is out of range"))?;
                        budget.max_requests_per_tick = parsed;
                    }
                    if let Some(n) = args.get("targetItems").and_then(Value::as_u64) {
                        budget.target_items = Some(
                            usize::try_from(n)
                                .map_err(|_| ToolError::new("targetItems is out of range"))?,
                        );
                    }
                    let max_depth = args
                        .get("maxDepth")
                        .and_then(Value::as_u64)
                        .map(|n| usize::try_from(n).unwrap_or(usize::MAX))
                        .unwrap_or(2);
                    let req = CreateSourceRequest {
                        id: args
                            .get("sourceId")
                            .and_then(Value::as_str)
                            .map(str::to_string),
                        name: args.get("name").and_then(Value::as_str).map(str::to_string),
                        seeds,
                        include_paths: string_vec(&args, "includePaths")?,
                        exclude_paths: string_vec(&args, "excludePaths")?,
                        max_depth,
                        allow_subdomains: args
                            .get("allowSubdomains")
                            .and_then(Value::as_bool)
                            .unwrap_or(false),
                        freshness: FreshnessPolicy::default(),
                        budget,
                        extract_schema: None,
                        extract_prompt: None,
                        required_fields: string_vec(&args, "requiredFields")?,
                        allow_browser: args
                            .get("allowBrowser")
                            .and_then(Value::as_bool)
                            .unwrap_or(true),
                    };
                    let spec = build_source_spec(req, None).map_err(bad)?;
                    let saved = store
                        .blocking(move |st| st.sync().upsert_source(spec))
                        .await
                        .map_err(|e| ToolError::new(format!("save source failed: {e}")))?;
                    Ok(ToolOutput::json(
                        json!({ "success": true, "action": "create", "source": saved }),
                    ))
                }
                "list" => {
                    let sources = store
                        .blocking(|st| st.sync().list_sources())
                        .await
                        .map_err(|e| ToolError::new(format!("list sources failed: {e}")))?;
                    Ok(ToolOutput::json(json!({
                        "success": true,
                        "action": "list",
                        "total": sources.len(),
                        "sources": sources,
                    })))
                }
                "get" => {
                    let id = require_source_id(&args)?;
                    let lookup = id.clone();
                    let source = store
                        .blocking(move |st| st.sync().get_source(&lookup))
                        .await
                        .map_err(|e| ToolError::new(format!("get source failed: {e}")))?
                        .ok_or_else(|| ToolError::new(format!("data source '{id}' not found")))?;
                    Ok(ToolOutput::json(json!({
                        "success": true,
                        "action": "get",
                        "source": source,
                    })))
                }
                "delete" => {
                    let id = require_source_id(&args)?;
                    let del_id = id.clone();
                    let deleted = store
                        .blocking(move |st| st.sync().delete_source(&del_id))
                        .await
                        .map_err(|e| ToolError::new(format!("delete source failed: {e}")))?;
                    Ok(ToolOutput::json(json!({
                        "success": true,
                        "action": "delete",
                        "id": id,
                        "deleted": deleted,
                    })))
                }
                "run" => {
                    let id = require_source_id(&args)?;
                    let force_all = args
                        .get("forceAll")
                        .and_then(Value::as_bool)
                        .unwrap_or(false);
                    let max_requests = match args.get("maxRequests").and_then(Value::as_u64) {
                        Some(0) => return Err(ToolError::new("maxRequests must be >= 1")),
                        Some(n) => {
                            let v = usize::try_from(n)
                                .map_err(|_| ToolError::new("maxRequests is out of range"))?;
                            pagesift_api::sources::validate_max_requests(Some(v)).map_err(bad)?
                        }
                        None => None,
                    };
                    let delta = self
                        .engine
                        .sync_source(&id, None, force_all, max_requests)
                        .await
                        .map_err(bad)?;
                    Ok(ToolOutput::json(json!({
                        "success": true,
                        "action": "run",
                        "delta": delta,
                    })))
                }
                "state" => {
                    let id = require_source_id(&args)?;
                    let as_of_ms = parse_as_of_arg(&args)?;
                    let lookup = id.clone();
                    let state = store
                        .blocking(move |st| st.sync().build_state_view(&lookup, as_of_ms))
                        .await
                        .map_err(|e| ToolError::new(format!("build state view failed: {e}")))?
                        .ok_or_else(|| ToolError::new(format!("data source '{id}' not found")))?;
                    Ok(ToolOutput::json(json!({
                        "success": true,
                        "action": "state",
                        "state": state,
                    })))
                }
                "deltas" => {
                    let id = require_source_id(&args)?;
                    let tick_id = args
                        .get("tickId")
                        .and_then(Value::as_str)
                        .map(str::trim)
                        .filter(|s| !s.is_empty())
                        .map(str::to_string);
                    if let Some(tick) = tick_id {
                        let lookup = id.clone();
                        let lookup_tick = tick.clone();
                        let (exists, delta) = store
                            .blocking(move |st| -> Result<_, pagesift_store::Error> {
                                let sync = st.sync();
                                if sync.get_source(&lookup)?.is_none() {
                                    return Ok((false, None));
                                }
                                Ok((true, sync.get_delta(&lookup, &lookup_tick)?))
                            })
                            .await
                            .map_err(|e| ToolError::new(format!("get delta failed: {e}")))?;
                        if !exists {
                            return Err(ToolError::new(format!("data source '{id}' not found")));
                        }
                        let delta = delta.ok_or_else(|| {
                            ToolError::new(format!("delta '{tick}' for '{id}' not found"))
                        })?;
                        return Ok(ToolOutput::json(json!({
                            "success": true,
                            "action": "deltas",
                            "delta": delta,
                        })));
                    }
                    let limit = args
                        .get("limit")
                        .and_then(Value::as_u64)
                        .map(|n| usize::try_from(n).unwrap_or(MAX_DELTAS_PER_SOURCE))
                        .unwrap_or(20)
                        .clamp(1, MAX_DELTAS_PER_SOURCE);
                    let lookup = id.clone();
                    let deltas = store
                        .blocking(move |st| {
                            let sync = st.sync();
                            if sync.get_source(&lookup)?.is_none() {
                                return Ok::<_, pagesift_store::Error>(None);
                            }
                            Ok(Some(sync.list_deltas(&lookup, limit)?))
                        })
                        .await
                        .map_err(|e| ToolError::new(format!("list deltas failed: {e}")))?
                        .ok_or_else(|| ToolError::new(format!("data source '{id}' not found")))?;
                    Ok(ToolOutput::json(json!({
                        "success": true,
                        "action": "deltas",
                        "total": deltas.len(),
                        "deltas": deltas,
                    })))
                }
                other => Err(ToolError::new(format!("unsupported sync action {other:?}"))),
            }
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use pagesift_api::BoxFuture;
    use pagesift_api::types::{Document, ScrapeOptions};

    struct DummyEngine;

    impl Engine for DummyEngine {
        fn scrape<'a>(
            &'a self,
            _url: &'a str,
            _opts: &'a ScrapeOptions,
        ) -> BoxFuture<'a, Result<Document, ApiError>> {
            Box::pin(async { Err(ApiError::unsupported("unused")) })
        }
    }

    #[tokio::test]
    async fn sync_tool_manages_sources_and_queries_state() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open_dir(dir.path()).unwrap();
        let tool = SyncTool {
            engine: Arc::new(DummyEngine),
            store: Some(store),
        };
        let ctx = ToolContext::default();

        let created = tool
            .call(
                json!({
                    "action": "create",
                    "sourceId": "docs-src",
                    "seeds": ["https://example.com/docs"],
                    "requiredFields": ["price"]
                })
                .as_object()
                .unwrap()
                .clone(),
                ctx.clone(),
            )
            .await
            .unwrap();
        let created_json = created.structured_content.unwrap();
        assert_eq!(created_json["source"]["id"], "docs-src");

        let listed = tool
            .call(
                json!({"action": "list"}).as_object().unwrap().clone(),
                ctx.clone(),
            )
            .await
            .unwrap();
        assert_eq!(listed.structured_content.unwrap()["total"], 1);

        let inst_a = created_json["source"]["instanceId"]
            .as_str()
            .unwrap()
            .to_string();
        assert!(!inst_a.is_empty());

        let state = tool
            .call(
                json!({"action": "state", "sourceId": "docs-src"})
                    .as_object()
                    .unwrap()
                    .clone(),
                ctx.clone(),
            )
            .await
            .unwrap();
        assert_eq!(
            state.structured_content.unwrap()["state"]["spec"]["id"],
            "docs-src"
        );

        let deleted = tool
            .call(
                json!({"action": "delete", "sourceId": "docs-src"})
                    .as_object()
                    .unwrap()
                    .clone(),
                ctx.clone(),
            )
            .await
            .unwrap();
        assert_eq!(deleted.structured_content.unwrap()["deleted"], true);

        let miss_delta = tool
            .call(
                json!({"action": "deltas", "sourceId": "docs-src", "tickId": "t1"})
                    .as_object()
                    .unwrap()
                    .clone(),
                ctx.clone(),
            )
            .await
            .unwrap_err();
        assert!(
            miss_delta
                .message
                .contains("data source 'docs-src' not found")
        );

        let recreated = tool
            .call(
                json!({
                    "action": "create",
                    "sourceId": "docs-src",
                    "seeds": ["https://example.com/docs"]
                })
                .as_object()
                .unwrap()
                .clone(),
                ctx,
            )
            .await
            .unwrap();
        let inst_b = recreated.structured_content.unwrap()["source"]["instanceId"]
            .as_str()
            .unwrap()
            .to_string();
        assert_ne!(inst_a, inst_b);
    }
}