scraps 1.0.1

Scraps is a portable CLI knowledge hub for managing interconnected Markdown documentation with Wiki-link notation.
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
use std::path::PathBuf;

use super::tools::get_scrap::{get_scrap, GetScrapRequest};
use super::tools::list_tags::list_tags;
use super::tools::lookup_scrap_backlinks::{lookup_scrap_backlinks, LookupScrapBacklinksRequest};
use super::tools::lookup_scrap_links::{lookup_scrap_links, LookupScrapLinksRequest};
use super::tools::lookup_tag_backlinks::{lookup_tag_backlinks, LookupTagBacklinksRequest};
use super::tools::search_scraps::{search_scraps, SearchRequest};
use rmcp::handler::server::tool::ToolRouter;
use rmcp::handler::server::wrapper::Parameters;
use rmcp::handler::server::ServerHandler;
use rmcp::model::{CallToolResult, ServerCapabilities, ServerInfo};
use rmcp::service::RequestContext;
use rmcp::{tool, tool_handler, tool_router, ErrorData, RoleServer};

pub struct ScrapsServer {
    tool_router: ToolRouter<ScrapsServer>,
    scraps_dir: PathBuf,
    exclude_dirs: Vec<PathBuf>,
}

impl ScrapsServer {
    pub fn new(scraps_dir: PathBuf, exclude_dirs: Vec<PathBuf>) -> Self {
        Self {
            tool_router: Self::tool_router(),
            scraps_dir,
            exclude_dirs,
        }
    }
}

#[tool_router]
impl ScrapsServer {
    #[tool(
        description = "Get a single scrap by title and optional context. Optionally restrict to a heading section via 'heading'. Optionally project specific fields via 'fields' (allowed: title, ctx, body, headings, code_blocks); defaults to ['title', 'ctx', 'body']."
    )]
    async fn get_scrap(
        &self,
        context: RequestContext<RoleServer>,
        parameters: Parameters<GetScrapRequest>,
    ) -> Result<CallToolResult, ErrorData> {
        get_scrap(&self.scraps_dir, &self.exclude_dirs, context, parameters).await
    }

    #[tool(
        description = "Search for scraps using fuzzy matching against title and body content. Space-separated keywords use OR logic by default (any keyword matches). Set logic to 'and' for all keywords to match. Returns matching scraps with titles and contexts. Use get_scrap to retrieve full content."
    )]
    async fn search_scraps(
        &self,
        context: RequestContext<RoleServer>,
        parameters: Parameters<SearchRequest>,
    ) -> Result<CallToolResult, ErrorData> {
        search_scraps(&self.scraps_dir, &self.exclude_dirs, context, parameters).await
    }

    #[tool(
        description = "Lookup outbound wiki links from a specific scrap. Returns all scraps that the specified scrap links to. Use get_scrap to retrieve full content."
    )]
    async fn lookup_scrap_links(
        &self,
        context: RequestContext<RoleServer>,
        parameters: Parameters<LookupScrapLinksRequest>,
    ) -> Result<CallToolResult, ErrorData> {
        lookup_scrap_links(&self.scraps_dir, &self.exclude_dirs, context, parameters).await
    }

    #[tool(
        description = "Lookup inbound wiki links (backlinks) to a specific scrap. Returns all scraps that link to the specified scrap. Use get_scrap to retrieve full content."
    )]
    async fn lookup_scrap_backlinks(
        &self,
        context: RequestContext<RoleServer>,
        parameters: Parameters<LookupScrapBacklinksRequest>,
    ) -> Result<CallToolResult, ErrorData> {
        lookup_scrap_backlinks(&self.scraps_dir, &self.exclude_dirs, context, parameters).await
    }

    #[tool(
        description = "List all available tags used across scraps in the documentation site. Useful for discovering content categories and topics."
    )]
    async fn list_tags(
        &self,
        context: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, ErrorData> {
        list_tags(&self.scraps_dir, &self.exclude_dirs, context).await
    }

    #[tool(
        description = "Lookup inbound references (backlinks) to a specific tag. Returns all scraps that reference the specified tag. Use get_scrap to retrieve full content."
    )]
    async fn lookup_tag_backlinks(
        &self,
        context: RequestContext<RoleServer>,
        parameters: Parameters<LookupTagBacklinksRequest>,
    ) -> Result<CallToolResult, ErrorData> {
        lookup_tag_backlinks(&self.scraps_dir, &self.exclude_dirs, context, parameters).await
    }
}

#[tool_handler]
impl ServerHandler for ScrapsServer {
    fn get_info(&self) -> ServerInfo {
        ServerInfo::new(ServerCapabilities::builder().enable_tools().build())
            .with_instructions("This is a Scraps MCP server")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_fixtures::{temp_scrap_project, TempScrapProject};
    use rmcp::model::CallToolRequestParams;
    use rmcp::ServiceExt;
    use rstest::rstest;

    #[rstest]
    fn test_server_info(#[from(temp_scrap_project)] project: TempScrapProject) {
        let server = ScrapsServer::new(
            project.scraps_dir.clone(),
            vec![project.static_dir.clone(), project.output_dir.clone()],
        );
        let info = server.get_info();

        assert_eq!(
            info.instructions,
            Some("This is a Scraps MCP server".into())
        );
        assert!(info.capabilities.tools.is_some());
    }

    #[rstest]
    #[tokio::test]
    async fn test_list_tools(#[from(temp_scrap_project)] project: TempScrapProject) {
        let server = ScrapsServer::new(
            project.scraps_dir.clone(),
            vec![project.static_dir.clone(), project.output_dir.clone()],
        );

        let (client_stream, server_stream) = tokio::io::duplex(4096);

        let server_handle = tokio::spawn(async move { server.serve(server_stream).await });

        let client = ().serve(client_stream).await.unwrap();

        let tools = client.list_tools(Default::default()).await.unwrap();

        assert_eq!(tools.tools.len(), 6);

        let tool_names: Vec<&str> = tools.tools.iter().map(|t| t.name.as_ref()).collect();
        assert!(tool_names.contains(&"get_scrap"));
        assert!(tool_names.contains(&"search_scraps"));
        assert!(tool_names.contains(&"lookup_scrap_links"));
        assert!(tool_names.contains(&"lookup_scrap_backlinks"));
        assert!(tool_names.contains(&"list_tags"));
        assert!(tool_names.contains(&"lookup_tag_backlinks"));

        client.cancel().await.unwrap();
        server_handle.abort();
    }

    #[rstest]
    #[tokio::test]
    async fn test_call_search_scraps(#[from(temp_scrap_project)] project: TempScrapProject) {
        project.add_scrap("test.md", b"# Test Scrap\n\nContent here");

        let server = ScrapsServer::new(
            project.scraps_dir.clone(),
            vec![project.static_dir.clone(), project.output_dir.clone()],
        );

        let (client_stream, server_stream) = tokio::io::duplex(4096);

        let server_handle = tokio::spawn(async move { server.serve(server_stream).await });

        let client = ().serve(client_stream).await.unwrap();

        let result = client
            .call_tool(
                CallToolRequestParams::new("search_scraps").with_arguments(
                    serde_json::json!({"query": "test"})
                        .as_object()
                        .unwrap()
                        .clone(),
                ),
            )
            .await
            .unwrap();

        assert!(!result.is_error.unwrap_or(false));
        assert!(!result.content.is_empty());

        let content_text = result.content[0].as_text().unwrap();
        let response: serde_json::Value = serde_json::from_str(&content_text.text).unwrap();
        assert!(response["count"].as_u64().unwrap() > 0);
        assert!(content_text.text.contains("test"));
        assert!(
            !content_text.text.contains("md_text"),
            "search_scraps should not include md_text"
        );

        client.cancel().await.unwrap();
        server_handle.abort();
    }

    #[rstest]
    #[tokio::test]
    async fn test_call_get_scrap(#[from(temp_scrap_project)] project: TempScrapProject) {
        project.add_scrap("test.md", b"# Test Scrap\n\nContent here");

        let server = ScrapsServer::new(
            project.scraps_dir.clone(),
            vec![project.static_dir.clone(), project.output_dir.clone()],
        );

        let (client_stream, server_stream) = tokio::io::duplex(4096);

        let server_handle = tokio::spawn(async move { server.serve(server_stream).await });

        let client = ().serve(client_stream).await.unwrap();

        let result = client
            .call_tool(
                CallToolRequestParams::new("get_scrap").with_arguments(
                    serde_json::json!({"title": "test"})
                        .as_object()
                        .unwrap()
                        .clone(),
                ),
            )
            .await
            .unwrap();

        assert!(!result.is_error.unwrap_or(false));
        assert!(!result.content.is_empty());

        let content_text = result.content[0].as_text().unwrap();
        assert!(content_text.text.contains("Test Scrap"));
        assert!(content_text.text.contains("Content here"));

        client.cancel().await.unwrap();
        server_handle.abort();
    }

    #[rstest]
    #[tokio::test]
    async fn test_call_list_tags(#[from(temp_scrap_project)] project: TempScrapProject) {
        project.add_scrap("test.md", b"#[[rust]] #[[programming]]");

        let server = ScrapsServer::new(
            project.scraps_dir.clone(),
            vec![project.static_dir.clone(), project.output_dir.clone()],
        );

        let (client_stream, server_stream) = tokio::io::duplex(4096);

        let server_handle = tokio::spawn(async move { server.serve(server_stream).await });

        let client = ().serve(client_stream).await.unwrap();

        let result = client
            .call_tool(CallToolRequestParams::new("list_tags"))
            .await
            .unwrap();

        assert!(!result.is_error.unwrap_or(false));
        assert!(!result.content.is_empty());

        let content_text = result.content[0].as_text().unwrap();
        assert!(
            content_text.text.contains("rust") || content_text.text.contains("programming"),
            "Expected tags in response, got: {}",
            content_text.text
        );

        client.cancel().await.unwrap();
        server_handle.abort();
    }

    #[rstest]
    #[tokio::test]
    async fn test_call_lookup_scrap_links(#[from(temp_scrap_project)] project: TempScrapProject) {
        project.add_scrap("source.md", b"# Source\n\n[[target]]");
        project.add_scrap("target.md", b"# Target\n\nTarget content");

        let server = ScrapsServer::new(
            project.scraps_dir.clone(),
            vec![project.static_dir.clone(), project.output_dir.clone()],
        );

        let (client_stream, server_stream) = tokio::io::duplex(4096);

        let server_handle = tokio::spawn(async move { server.serve(server_stream).await });

        let client = ().serve(client_stream).await.unwrap();

        let result = client
            .call_tool(
                CallToolRequestParams::new("lookup_scrap_links").with_arguments(
                    serde_json::json!({"title": "source"})
                        .as_object()
                        .unwrap()
                        .clone(),
                ),
            )
            .await
            .unwrap();

        assert!(!result.is_error.unwrap_or(false));
        assert!(!result.content.is_empty());

        let content_text = result.content[0].as_text().unwrap();
        assert!(content_text.text.contains("target"));

        client.cancel().await.unwrap();
        server_handle.abort();
    }

    #[rstest]
    #[tokio::test]
    async fn test_call_lookup_scrap_backlinks(
        #[from(temp_scrap_project)] project: TempScrapProject,
    ) {
        project.add_scrap("source.md", b"# Source\n\n[[target]]");
        project.add_scrap("target.md", b"# Target\n\nTarget content");

        let server = ScrapsServer::new(
            project.scraps_dir.clone(),
            vec![project.static_dir.clone(), project.output_dir.clone()],
        );

        let (client_stream, server_stream) = tokio::io::duplex(4096);

        let server_handle = tokio::spawn(async move { server.serve(server_stream).await });

        let client = ().serve(client_stream).await.unwrap();

        let result = client
            .call_tool(
                CallToolRequestParams::new("lookup_scrap_backlinks").with_arguments(
                    serde_json::json!({"title": "target"})
                        .as_object()
                        .unwrap()
                        .clone(),
                ),
            )
            .await
            .unwrap();

        assert!(!result.is_error.unwrap_or(false));
        assert!(!result.content.is_empty());

        let content_text = result.content[0].as_text().unwrap();
        assert!(content_text.text.contains("source"));

        client.cancel().await.unwrap();
        server_handle.abort();
    }

    #[rstest]
    #[tokio::test]
    async fn test_call_lookup_tag_backlinks(#[from(temp_scrap_project)] project: TempScrapProject) {
        project.add_scrap("test.md", b"# Test\n\n#[[rust]]");

        let server = ScrapsServer::new(
            project.scraps_dir.clone(),
            vec![project.static_dir.clone(), project.output_dir.clone()],
        );

        let (client_stream, server_stream) = tokio::io::duplex(4096);

        let server_handle = tokio::spawn(async move { server.serve(server_stream).await });

        let client = ().serve(client_stream).await.unwrap();

        let result = client
            .call_tool(
                CallToolRequestParams::new("lookup_tag_backlinks").with_arguments(
                    serde_json::json!({"tag": "rust"})
                        .as_object()
                        .unwrap()
                        .clone(),
                ),
            )
            .await
            .unwrap();

        assert!(!result.is_error.unwrap_or(false));
        assert!(!result.content.is_empty());

        let content_text = result.content[0].as_text().unwrap();
        assert!(
            content_text.text.contains("Test") || content_text.text.contains("test"),
            "Expected scrap with tag 'rust' in response, got: {}",
            content_text.text
        );

        client.cancel().await.unwrap();
        server_handle.abort();
    }

    /// Test: search_scraps with AND logic (default) - all keywords must match
    #[rstest]
    #[tokio::test]
    async fn test_call_search_scraps_and_logic(
        #[from(temp_scrap_project)] project: TempScrapProject,
    ) {
        // Setup: 3 scraps - only one contains both "rust" and "python"
        project.add_scrap("rust_doc.md", b"# Rust Documentation\n\nRust content");
        project.add_scrap("python_doc.md", b"# Python Documentation\n\nPython content");
        project.add_scrap("rust_python.md", b"# Rust and Python\n\nBoth languages");

        let server = ScrapsServer::new(
            project.scraps_dir.clone(),
            vec![project.static_dir.clone(), project.output_dir.clone()],
        );

        let (client_stream, server_stream) = tokio::io::duplex(4096);

        let server_handle = tokio::spawn(async move { server.serve(server_stream).await });

        let client = ().serve(client_stream).await.unwrap();

        // AND search: "rust python" should only match "rust_python.md"
        let result = client
            .call_tool(
                CallToolRequestParams::new("search_scraps").with_arguments(
                    serde_json::json!({"query": "rust python", "logic": "and"})
                        .as_object()
                        .unwrap()
                        .clone(),
                ),
            )
            .await
            .unwrap();

        assert!(!result.is_error.unwrap_or(false));
        assert!(!result.content.is_empty());

        let content_text = result.content[0].as_text().unwrap();
        // Parse the JSON response to check count
        let response: serde_json::Value = serde_json::from_str(&content_text.text).unwrap();
        assert_eq!(
            response["count"], 1,
            "AND search should return only 1 result matching both keywords"
        );
        assert!(
            content_text.text.contains("rust_python"),
            "AND search should match the scrap containing both keywords"
        );

        client.cancel().await.unwrap();
        server_handle.abort();
    }

    /// Test: search_scraps with OR logic - any keyword can match
    #[rstest]
    #[tokio::test]
    async fn test_call_search_scraps_or_logic(
        #[from(temp_scrap_project)] project: TempScrapProject,
    ) {
        // Setup: 3 scraps - all contain either "rust" or "python"
        project.add_scrap("rust_doc.md", b"# Rust Documentation\n\nRust content");
        project.add_scrap("python_doc.md", b"# Python Documentation\n\nPython content");
        project.add_scrap("rust_python.md", b"# Rust and Python\n\nBoth languages");

        let server = ScrapsServer::new(
            project.scraps_dir.clone(),
            vec![project.static_dir.clone(), project.output_dir.clone()],
        );

        let (client_stream, server_stream) = tokio::io::duplex(4096);

        let server_handle = tokio::spawn(async move { server.serve(server_stream).await });

        let client = ().serve(client_stream).await.unwrap();

        // OR search: "rust python" should match all 3 scraps
        let result = client
            .call_tool(
                CallToolRequestParams::new("search_scraps").with_arguments(
                    serde_json::json!({"query": "rust python", "logic": "or"})
                        .as_object()
                        .unwrap()
                        .clone(),
                ),
            )
            .await
            .unwrap();

        assert!(!result.is_error.unwrap_or(false));
        assert!(!result.content.is_empty());

        let content_text = result.content[0].as_text().unwrap();
        // Parse the JSON response to check count
        let response: serde_json::Value = serde_json::from_str(&content_text.text).unwrap();
        assert_eq!(
            response["count"], 3,
            "OR search should return all 3 results matching any keyword"
        );

        client.cancel().await.unwrap();
        server_handle.abort();
    }
}