daedra 0.2.0

Self-contained web search MCP server. 9 backends with automatic fallback. Works from any IP.
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
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
//! Common types and data structures used throughout Daedra.
//!
//! This module contains all the shared types including:
//! - Search arguments and results
//! - Error types
//! - Configuration structures

use serde::{Deserialize, Serialize};
use thiserror::Error;

/// Result type alias for Daedra operations
pub type DaedraResult<T> = Result<T, DaedraError>;

/// Errors that can occur during Daedra operations
#[derive(Error, Debug)]
pub enum DaedraError {
    /// HTTP request failed
    #[error("HTTP request failed: {0}")]
    HttpError(#[from] reqwest::Error),

    /// URL parsing failed
    #[error("Invalid URL: {0}")]
    UrlParseError(#[from] url::ParseError),

    /// JSON serialization/deserialization failed
    #[error("JSON error: {0}")]
    JsonError(#[from] serde_json::Error),

    /// Search operation failed
    #[error("Search failed: {0}")]
    SearchError(String),

    /// Page fetch failed
    #[error("Failed to fetch page: {0}")]
    FetchError(String),

    /// Invalid arguments provided
    #[error("Invalid arguments: {0}")]
    InvalidArguments(String),

    /// Server error
    #[error("Server error: {0}")]
    ServerError(String),

    /// IO error
    #[error("IO error: {0}")]
    IoError(#[from] std::io::Error),

    /// Content extraction failed
    #[error("Content extraction failed: {0}")]
    ExtractionError(String),

    /// Rate limit exceeded
    #[error("Rate limit exceeded, please try again later")]
    RateLimitExceeded,

    /// Bot protection detected
    #[error("Bot protection detected on target page")]
    BotProtectionDetected,

    /// Timeout occurred
    #[error("Operation timed out")]
    Timeout,
}

/// Safe search filtering levels
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "UPPERCASE")]
pub enum SafeSearchLevel {
    /// No filtering
    Off,
    /// Moderate filtering (default)
    #[default]
    Moderate,
    /// Strict filtering
    Strict,
}

impl SafeSearchLevel {
    /// Convert to DuckDuckGo safe search parameter value
    pub fn to_ddg_value(&self) -> i32 {
        match self {
            SafeSearchLevel::Off => -2,
            SafeSearchLevel::Moderate => -1,
            SafeSearchLevel::Strict => 1,
        }
    }
}

impl std::fmt::Display for SafeSearchLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SafeSearchLevel::Off => write!(f, "OFF"),
            SafeSearchLevel::Moderate => write!(f, "MODERATE"),
            SafeSearchLevel::Strict => write!(f, "STRICT"),
        }
    }
}

impl std::str::FromStr for SafeSearchLevel {
    type Err = DaedraError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_uppercase().as_str() {
            "OFF" => Ok(SafeSearchLevel::Off),
            "MODERATE" => Ok(SafeSearchLevel::Moderate),
            "STRICT" => Ok(SafeSearchLevel::Strict),
            _ => Err(DaedraError::InvalidArguments(format!(
                "Invalid safe search level: {}",
                s
            ))),
        }
    }
}

/// Options for search operations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchOptions {
    /// Region for search results (e.g., "us-en", "zh-cn")
    #[serde(default = "default_region")]
    pub region: String,

    /// Safe search filtering level
    #[serde(default)]
    pub safe_search: SafeSearchLevel,

    /// Maximum number of results to return
    #[serde(default = "default_num_results")]
    pub num_results: usize,

    /// Time range filter (e.g., "d" for day, "w" for week, "m" for month)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time_range: Option<String>,
}

impl Default for SearchOptions {
    fn default() -> Self {
        Self {
            region: "wt-wt".to_string(),
            safe_search: SafeSearchLevel::Moderate,
            num_results: 10,
            time_range: None,
        }
    }
}

fn default_region() -> String {
    "wt-wt".to_string() // Worldwide
}

fn default_num_results() -> usize {
    10
}

/// Arguments for the search tool
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchArgs {
    /// The search query string
    pub query: String,

    /// Optional search configuration
    #[serde(skip_serializing_if = "Option::is_none")]
    pub options: Option<SearchOptions>,
}

/// Arguments for the visit_page tool
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VisitPageArgs {
    /// URL of the page to visit
    pub url: String,

    /// Optional CSS selector to target specific content
    #[serde(skip_serializing_if = "Option::is_none")]
    pub selector: Option<String>,

    /// Whether to include images in the response
    #[serde(default)]
    pub include_images: bool,
}

/// Content type classification for search results
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[derive(Default)]
pub enum ContentType {
    /// Documentation pages
    Documentation,
    /// Social media content
    Social,
    /// News articles
    Article,
    /// Forum discussions
    Forum,
    /// Video content
    Video,
    /// E-commerce/shopping
    Shopping,
    /// Other/unknown content
    #[default]
    Other,
}

/// Metadata for a search result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResultMetadata {
    /// Content type classification
    #[serde(rename = "type")]
    pub content_type: ContentType,

    /// Source domain
    pub source: String,

    /// Favicon URL if available
    #[serde(skip_serializing_if = "Option::is_none")]
    pub favicon: Option<String>,

    /// Published date if available
    #[serde(skip_serializing_if = "Option::is_none")]
    pub published_date: Option<String>,
}

/// A single search result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchResult {
    /// Title of the result
    pub title: String,

    /// URL of the result
    pub url: String,

    /// Description/snippet
    pub description: String,

    /// Additional metadata
    pub metadata: ResultMetadata,
}

/// Query analysis information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueryAnalysis {
    /// Detected language of the query
    pub language: String,

    /// Detected topics in results
    pub topics: Vec<String>,
}

/// Search context information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchContext {
    /// Region used for search
    pub region: String,

    /// Safe search level applied
    pub safe_search: String,

    /// Number of results requested
    #[serde(skip_serializing_if = "Option::is_none")]
    pub num_results: Option<usize>,
}

/// Metadata about the search operation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchMetadata {
    /// Original search query
    pub query: String,

    /// ISO timestamp of when search was conducted
    pub timestamp: String,

    /// Number of results returned
    pub result_count: usize,

    /// Search context information
    pub search_context: SearchContext,

    /// Query analysis results
    pub query_analysis: QueryAnalysis,
}

/// Complete search response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchResponse {
    /// Response type discriminator
    #[serde(rename = "type")]
    pub response_type: String,

    /// Array of search results
    pub data: Vec<SearchResult>,

    /// Search metadata
    pub metadata: SearchMetadata,
}

impl SearchResponse {
    /// Create a new search response
    pub fn new(query: String, results: Vec<SearchResult>, options: &SearchOptions) -> Self {
        let timestamp = chrono::Utc::now().to_rfc3339();
        let result_count = results.len();

        // Analyze query for language detection
        let language = detect_language(&query);
        let topics = detect_topics(&results);

        Self {
            response_type: "search_results".to_string(),
            data: results,
            metadata: SearchMetadata {
                query,
                timestamp,
                result_count,
                search_context: SearchContext {
                    region: options.region.clone(),
                    safe_search: options.safe_search.to_string(),
                    num_results: Some(options.num_results),
                },
                query_analysis: QueryAnalysis { language, topics },
            },
        }
    }
}

/// Result of visiting a page
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PageContent {
    /// URL of the page
    pub url: String,

    /// Page title
    pub title: String,

    /// Extracted content in Markdown format
    pub content: String,

    /// ISO timestamp of when page was fetched
    pub timestamp: String,

    /// Word count of extracted content
    pub word_count: usize,

    /// Links found on the page
    #[serde(skip_serializing_if = "Option::is_none")]
    pub links: Option<Vec<PageLink>>,
}

/// A link found on a page
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PageLink {
    /// Link text
    pub text: String,

    /// Link URL
    pub url: String,
}

/// Detect language of a query using simple heuristics
fn detect_language(query: &str) -> String {
    // Check for Chinese characters
    if query
        .chars()
        .any(|c| ('\u{4e00}'..='\u{9fff}').contains(&c))
    {
        return "zh".to_string();
    }

    // Check for Japanese characters (Hiragana/Katakana)
    if query
        .chars()
        .any(|c| ('\u{3040}'..='\u{30ff}').contains(&c))
    {
        return "ja".to_string();
    }

    // Check for Korean characters
    if query
        .chars()
        .any(|c| ('\u{ac00}'..='\u{d7af}').contains(&c))
    {
        return "ko".to_string();
    }

    // Check for Cyrillic
    if query
        .chars()
        .any(|c| ('\u{0400}'..='\u{04ff}').contains(&c))
    {
        return "ru".to_string();
    }

    // Check for Arabic
    if query
        .chars()
        .any(|c| ('\u{0600}'..='\u{06ff}').contains(&c))
    {
        return "ar".to_string();
    }

    // Default to English
    "en".to_string()
}

/// Detect topics from search results
fn detect_topics(results: &[SearchResult]) -> Vec<String> {
    use std::collections::HashSet;

    let mut topics = HashSet::new();

    for result in results {
        let lower_title = result.title.to_lowercase();
        let lower_url = result.url.to_lowercase();

        // Technology indicators
        if lower_url.contains("github.com")
            || lower_url.contains("stackoverflow.com")
            || lower_url.contains("gitlab.com")
            || lower_title.contains("programming")
            || lower_title.contains("code")
        {
            topics.insert("technology".to_string());
        }

        // Documentation indicators
        if lower_url.contains("docs.")
            || lower_url.contains("/docs/")
            || lower_url.contains("/documentation/")
            || lower_title.contains("documentation")
            || lower_title.contains("api reference")
        {
            topics.insert("documentation".to_string());
        }

        // News indicators
        if lower_url.contains("news.")
            || lower_url.contains("/news/")
            || result.metadata.content_type == ContentType::Article
        {
            topics.insert("news".to_string());
        }

        // Academic indicators
        if lower_url.contains(".edu")
            || lower_url.contains("arxiv.org")
            || lower_url.contains("scholar.google")
            || lower_title.contains("research")
            || lower_title.contains("study")
        {
            topics.insert("academic".to_string());
        }
    }

    topics.into_iter().collect()
}

/// JSON Schema for search arguments (used for MCP tool definition)
pub fn search_args_schema() -> serde_json::Value {
    serde_json::json!({
        "type": "object",
        "properties": {
            "query": {
                "type": "string",
                "description": "The search query string"
            },
            "options": {
                "type": "object",
                "description": "Optional search configuration",
                "properties": {
                    "region": {
                        "type": "string",
                        "description": "Region for search results (e.g., 'us-en', 'wt-wt' for worldwide)",
                        "default": "wt-wt"
                    },
                    "safe_search": {
                        "type": "string",
                        "enum": ["OFF", "MODERATE", "STRICT"],
                        "description": "Safe search filtering level",
                        "default": "MODERATE"
                    },
                    "num_results": {
                        "type": "integer",
                        "description": "Maximum number of results to return",
                        "default": 10,
                        "minimum": 1,
                        "maximum": 50
                    },
                    "time_range": {
                        "type": "string",
                        "description": "Time range filter (d=day, w=week, m=month, y=year)"
                    }
                }
            }
        },
        "required": ["query"]
    })
}

/// JSON Schema for visit_page arguments
pub fn visit_page_args_schema() -> serde_json::Value {
    serde_json::json!({
        "type": "object",
        "properties": {
            "url": {
                "type": "string",
                "format": "uri",
                "description": "URL of the page to visit"
            },
            "selector": {
                "type": "string",
                "description": "Optional CSS selector to target specific content"
            },
            "include_images": {
                "type": "boolean",
                "description": "Whether to include image references in the response",
                "default": false
            }
        },
        "required": ["url"]
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_safe_search_level_parsing() {
        assert_eq!(
            "OFF".parse::<SafeSearchLevel>().unwrap(),
            SafeSearchLevel::Off
        );
        assert_eq!(
            "MODERATE".parse::<SafeSearchLevel>().unwrap(),
            SafeSearchLevel::Moderate
        );
        assert_eq!(
            "STRICT".parse::<SafeSearchLevel>().unwrap(),
            SafeSearchLevel::Strict
        );
        assert_eq!(
            "moderate".parse::<SafeSearchLevel>().unwrap(),
            SafeSearchLevel::Moderate
        );
    }

    #[test]
    fn test_safe_search_ddg_value() {
        assert_eq!(SafeSearchLevel::Off.to_ddg_value(), -2);
        assert_eq!(SafeSearchLevel::Moderate.to_ddg_value(), -1);
        assert_eq!(SafeSearchLevel::Strict.to_ddg_value(), 1);
    }

    #[test]
    fn test_language_detection() {
        assert_eq!(detect_language("hello world"), "en");
        assert_eq!(detect_language("你好世界"), "zh");
        assert_eq!(detect_language("こんにちは"), "ja");
        assert_eq!(detect_language("안녕하세요"), "ko");
        assert_eq!(detect_language("привет"), "ru");
    }

    #[test]
    fn test_search_args_schema() {
        let schema = search_args_schema();
        assert!(schema["properties"]["query"].is_object());
        assert!(schema["properties"]["options"].is_object());
    }

    #[test]
    fn test_search_response_creation() {
        let results = vec![SearchResult {
            title: "Test".to_string(),
            url: "https://example.com".to_string(),
            description: "Test description".to_string(),
            metadata: ResultMetadata {
                content_type: ContentType::Article,
                source: "example.com".to_string(),
                favicon: None,
                published_date: None,
            },
        }];

        let options = SearchOptions::default();
        let response = SearchResponse::new("test query".to_string(), results, &options);

        assert_eq!(response.response_type, "search_results");
        assert_eq!(response.data.len(), 1);
        assert_eq!(response.metadata.query, "test query");
    }
}