kreuzberg 4.0.0.pre.rc.7 → 4.0.0.pre.rc.8

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.
@@ -1,5 +1,3 @@
1
- #![cfg(feature = "api")]
2
-
3
1
  //! REST API server for Kreuzberg document extraction.
4
2
  //!
5
3
  //! This module provides an Axum-based HTTP server for document extraction
@@ -384,7 +384,7 @@ mod tests {
384
384
  #[test]
385
385
  fn test_extract_text_with_page_breaks_no_breaks() {
386
386
  let docx_path =
387
- "/Users/naamanhirschfeld/workspace/kreuzberg-dev/kreuzberg/test_documents/documents/lorem_ipsum.docx";
387
+ std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../test_documents/documents/lorem_ipsum.docx");
388
388
  if let Ok(bytes) = std::fs::read(docx_path) {
389
389
  let result = extract_text_with_page_breaks(&bytes);
390
390
  if let Ok((text, boundaries)) = result {
@@ -585,7 +585,8 @@ mod tests {
585
585
  ..Default::default()
586
586
  };
587
587
 
588
- let pdf_path = "/Users/naamanhirschfeld/workspace/kreuzberg-dev/kreuzberg/fixtures/pdf/simple_text.pdf";
588
+ let pdf_path =
589
+ std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../test_documents/pdfs/google_doc_document.pdf");
589
590
  if let Ok(content) = std::fs::read(pdf_path) {
590
591
  let result = extractor.extract_bytes(&content, "application/pdf", &config).await;
591
592
  assert!(
@@ -608,7 +609,8 @@ mod tests {
608
609
  let extractor = PdfExtractor::new();
609
610
  let config = ExtractionConfig::default();
610
611
 
611
- let pdf_path = "/Users/naamanhirschfeld/workspace/kreuzberg-dev/kreuzberg/fixtures/pdf/simple_text.pdf";
612
+ let pdf_path =
613
+ std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../test_documents/pdfs/google_doc_document.pdf");
612
614
  if let Ok(content) = std::fs::read(pdf_path) {
613
615
  let result = extractor.extract_bytes(&content, "application/pdf", &config).await;
614
616
  assert!(
@@ -641,7 +643,8 @@ mod tests {
641
643
  ..Default::default()
642
644
  };
643
645
 
644
- let pdf_path = "/Users/naamanhirschfeld/workspace/kreuzberg-dev/kreuzberg/fixtures/pdf/simple_text.pdf";
646
+ let pdf_path =
647
+ std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../test_documents/pdfs/multi_page.pdf");
645
648
  if let Ok(content) = std::fs::read(pdf_path) {
646
649
  let result = extractor.extract_bytes(&content, "application/pdf", &config).await;
647
650
  assert!(
@@ -1,5 +1,3 @@
1
- #![cfg(feature = "mcp")]
2
-
3
1
  //! Model Context Protocol (MCP) server implementation.
4
2
  //!
5
3
  //! Provides an MCP server that exposes Kreuzberg's document extraction
@@ -28,6 +26,9 @@ mod server;
28
26
 
29
27
  pub use server::{start_mcp_server, start_mcp_server_with_config};
30
28
 
29
+ #[cfg(feature = "mcp-http")]
30
+ pub use server::{start_mcp_server_http, start_mcp_server_http_with_config};
31
+
31
32
  pub use server::{BatchExtractFilesParams, DetectMimeTypeParams, ExtractBytesParams, ExtractFileParams, KreuzbergMcp};
32
33
 
33
34
  #[doc(hidden)]
@@ -12,6 +12,9 @@ use rmcp::{
12
12
  transport::stdio,
13
13
  };
14
14
 
15
+ #[cfg(feature = "mcp-http")]
16
+ use rmcp::transport::streamable_http_server::{StreamableHttpService, session::local::LocalSessionManager};
17
+
15
18
  use crate::{
16
19
  ExtractionConfig, ExtractionResult as KreuzbergResult, KreuzbergError, batch_extract_file, batch_extract_file_sync,
17
20
  cache, detect_mime_type, extract_bytes, extract_bytes_sync, extract_file, extract_file_sync,
@@ -453,6 +456,109 @@ pub async fn start_mcp_server_with_config(
453
456
  Ok(())
454
457
  }
455
458
 
459
+ /// Start MCP server with HTTP Stream transport.
460
+ ///
461
+ /// Uses rmcp's built-in StreamableHttpService for HTTP/SSE support per MCP spec.
462
+ ///
463
+ /// # Arguments
464
+ ///
465
+ /// * `host` - Host to bind to (e.g., "127.0.0.1" or "0.0.0.0")
466
+ /// * `port` - Port number (e.g., 8001)
467
+ ///
468
+ /// # Example
469
+ ///
470
+ /// ```no_run
471
+ /// use kreuzberg::mcp::start_mcp_server_http;
472
+ ///
473
+ /// #[tokio::main]
474
+ /// async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
475
+ /// start_mcp_server_http("127.0.0.1", 8001).await?;
476
+ /// Ok(())
477
+ /// }
478
+ /// ```
479
+ #[cfg(feature = "mcp-http")]
480
+ pub async fn start_mcp_server_http(
481
+ host: impl AsRef<str>,
482
+ port: u16,
483
+ ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
484
+ use axum::Router;
485
+ use std::net::SocketAddr;
486
+
487
+ let http_service = StreamableHttpService::new(
488
+ || KreuzbergMcp::new().map_err(|e| std::io::Error::other(e.to_string())),
489
+ LocalSessionManager::default().into(),
490
+ Default::default(),
491
+ );
492
+
493
+ let router = Router::new().nest_service("/mcp", http_service);
494
+
495
+ let addr: SocketAddr = format!("{}:{}", host.as_ref(), port)
496
+ .parse()
497
+ .map_err(|e| format!("Invalid address: {}", e))?;
498
+
499
+ #[cfg(feature = "api")]
500
+ tracing::info!("Starting MCP HTTP server on http://{}", addr);
501
+
502
+ let listener = tokio::net::TcpListener::bind(addr).await?;
503
+ axum::serve(listener, router).await?;
504
+
505
+ Ok(())
506
+ }
507
+
508
+ /// Start MCP HTTP server with custom extraction config.
509
+ ///
510
+ /// This variant allows specifying a custom extraction configuration
511
+ /// while using HTTP Stream transport.
512
+ ///
513
+ /// # Arguments
514
+ ///
515
+ /// * `host` - Host to bind to (e.g., "127.0.0.1" or "0.0.0.0")
516
+ /// * `port` - Port number (e.g., 8001)
517
+ /// * `config` - Custom extraction configuration
518
+ ///
519
+ /// # Example
520
+ ///
521
+ /// ```no_run
522
+ /// use kreuzberg::mcp::start_mcp_server_http_with_config;
523
+ /// use kreuzberg::ExtractionConfig;
524
+ ///
525
+ /// #[tokio::main]
526
+ /// async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
527
+ /// let config = ExtractionConfig::default();
528
+ /// start_mcp_server_http_with_config("127.0.0.1", 8001, config).await?;
529
+ /// Ok(())
530
+ /// }
531
+ /// ```
532
+ #[cfg(feature = "mcp-http")]
533
+ pub async fn start_mcp_server_http_with_config(
534
+ host: impl AsRef<str>,
535
+ port: u16,
536
+ config: ExtractionConfig,
537
+ ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
538
+ use axum::Router;
539
+ use std::net::SocketAddr;
540
+
541
+ let http_service = StreamableHttpService::new(
542
+ move || Ok(KreuzbergMcp::with_config(config.clone())),
543
+ LocalSessionManager::default().into(),
544
+ Default::default(),
545
+ );
546
+
547
+ let router = Router::new().nest_service("/mcp", http_service);
548
+
549
+ let addr: SocketAddr = format!("{}:{}", host.as_ref(), port)
550
+ .parse()
551
+ .map_err(|e| format!("Invalid address: {}", e))?;
552
+
553
+ #[cfg(feature = "api")]
554
+ tracing::info!("Starting MCP HTTP server on http://{}", addr);
555
+
556
+ let listener = tokio::net::TcpListener::bind(addr).await?;
557
+ axum::serve(listener, router).await?;
558
+
559
+ Ok(())
560
+ }
561
+
456
562
  /// Build extraction config from MCP parameters.
457
563
  ///
458
564
  /// Starts with the default config and overlays OCR settings from request parameters.
@@ -0,0 +1,328 @@
1
+ //! Runtime extraction of bundled PDFium library.
2
+ //!
3
+ //! When the `pdf-bundled` feature is enabled, the PDFium library is embedded in the binary
4
+ //! using `include_bytes!` during compilation. This module handles runtime extraction to a
5
+ //! temporary directory and provides the path for dynamic loading.
6
+ //!
7
+ //! # How It Works
8
+ //!
9
+ //! 1. During build (build.rs): PDFium is copied to OUT_DIR and the build script sets
10
+ //! `KREUZBERG_PDFIUM_BUNDLED_PATH` environment variable
11
+ //! 2. At compile time: `include_bytes!` embeds the library binary in the executable
12
+ //! 3. At runtime: `extract_bundled_pdfium()` extracts to `$TMPDIR/kreuzberg-pdfium/`
13
+ //! 4. Library is reused if already present (based on modification time)
14
+ //!
15
+ //! # Example
16
+ //!
17
+ //! ```rust,ignore
18
+ //! # #[cfg(feature = "pdf-bundled")]
19
+ //! # {
20
+ //! use kreuzberg::pdf::bundled::extract_bundled_pdfium;
21
+ //!
22
+ //! # fn example() -> kreuzberg::Result<()> {
23
+ //! let lib_path = extract_bundled_pdfium()?;
24
+ //! println!("Extracted to: {}", lib_path.display());
25
+ //! # Ok(())
26
+ //! # }
27
+ //! # }
28
+ //! ```
29
+
30
+ use std::fs;
31
+ use std::io;
32
+ use std::path::{Path, PathBuf};
33
+
34
+ #[cfg(unix)]
35
+ use std::os::unix::fs::PermissionsExt;
36
+
37
+ /// Runtime library name and extraction directory for the bundled PDFium library.
38
+ ///
39
+ /// Returns tuple of (library_name, extraction_directory)
40
+ fn bundled_library_info() -> (&'static str, &'static str) {
41
+ if cfg!(target_os = "windows") {
42
+ ("pdfium.dll", "kreuzberg-pdfium")
43
+ } else if cfg!(target_os = "macos") {
44
+ ("libpdfium.dylib", "kreuzberg-pdfium")
45
+ } else if cfg!(target_os = "linux") {
46
+ ("libpdfium.so", "kreuzberg-pdfium")
47
+ } else {
48
+ // Fallback for other Unix-like systems
49
+ ("libpdfium.so", "kreuzberg-pdfium")
50
+ }
51
+ }
52
+
53
+ /// Get the temporary directory for bundled PDFium extraction.
54
+ ///
55
+ /// Uses `std::env::temp_dir()` on all platforms.
56
+ fn get_extraction_dir() -> io::Result<PathBuf> {
57
+ let (_, subdir) = bundled_library_info();
58
+ Ok(std::env::temp_dir().join(subdir))
59
+ }
60
+
61
+ /// Check if extracted library exists and is valid.
62
+ ///
63
+ /// Verifies:
64
+ /// - File exists at expected path
65
+ /// - File size matches embedded size (basic validation)
66
+ ///
67
+ /// Returns `true` if library can be safely reused, `false` if extraction is needed.
68
+ fn is_extracted_library_valid(lib_path: &Path, embedded_size: usize) -> bool {
69
+ if !lib_path.exists() {
70
+ return false;
71
+ }
72
+
73
+ // Verify file size matches to catch partial/corrupted extractions
74
+ match fs::metadata(lib_path) {
75
+ Ok(metadata) => {
76
+ let file_size = metadata.len() as usize;
77
+ // Allow 1% size difference for platform-specific variations
78
+ let size_tolerance = (embedded_size as f64 * 0.01) as usize;
79
+ let min_size = embedded_size.saturating_sub(size_tolerance);
80
+ let max_size = embedded_size.saturating_add(size_tolerance);
81
+ file_size >= min_size && file_size <= max_size
82
+ }
83
+ Err(_) => false,
84
+ }
85
+ }
86
+
87
+ /// Extract bundled PDFium library to temporary directory.
88
+ ///
89
+ /// # Behavior
90
+ ///
91
+ /// - Embeds PDFium library using `include_bytes!`
92
+ /// - Extracts to `$TMPDIR/kreuzberg-pdfium/`
93
+ /// - Reuses extracted library if size matches
94
+ /// - Sets permissions to 0755 on Unix
95
+ /// - Returns path to extracted library
96
+ ///
97
+ /// # Errors
98
+ ///
99
+ /// Returns `std::io::Error` if:
100
+ /// - Cannot create extraction directory
101
+ /// - Cannot write library file
102
+ /// - Cannot set file permissions (Unix only)
103
+ ///
104
+ /// # Platform-Specific Library Names
105
+ ///
106
+ /// - Linux: `libpdfium.so`
107
+ /// - macOS: `libpdfium.dylib`
108
+ /// - Windows: `pdfium.dll`
109
+ pub fn extract_bundled_pdfium() -> io::Result<PathBuf> {
110
+ let (lib_name, _) = bundled_library_info();
111
+ let extract_dir = get_extraction_dir()?;
112
+
113
+ // Create extraction directory if it doesn't exist
114
+ fs::create_dir_all(&extract_dir).map_err(|e| {
115
+ io::Error::new(
116
+ e.kind(),
117
+ format!(
118
+ "Failed to create bundled pdfium extraction directory '{}': {}",
119
+ extract_dir.display(),
120
+ e
121
+ ),
122
+ )
123
+ })?;
124
+
125
+ let lib_path = extract_dir.join(lib_name);
126
+
127
+ // Include bundled PDFium library
128
+ let bundled_lib = include_bytes!(env!("KREUZBERG_PDFIUM_BUNDLED_PATH"));
129
+
130
+ // Check if library already exists and is valid
131
+ if is_extracted_library_valid(&lib_path, bundled_lib.len()) {
132
+ return Ok(lib_path);
133
+ }
134
+
135
+ // Write library to disk
136
+ fs::write(&lib_path, bundled_lib).map_err(|e| {
137
+ io::Error::new(
138
+ e.kind(),
139
+ format!(
140
+ "Failed to extract bundled pdfium library to '{}': {}",
141
+ lib_path.display(),
142
+ e
143
+ ),
144
+ )
145
+ })?;
146
+
147
+ // Set executable permissions on Unix
148
+ #[cfg(unix)]
149
+ {
150
+ let perms = fs::Permissions::from_mode(0o755);
151
+ fs::set_permissions(&lib_path, perms).map_err(|e| {
152
+ io::Error::new(
153
+ e.kind(),
154
+ format!(
155
+ "Failed to set permissions on bundled pdfium library '{}': {}",
156
+ lib_path.display(),
157
+ e
158
+ ),
159
+ )
160
+ })?;
161
+ }
162
+
163
+ Ok(lib_path)
164
+ }
165
+
166
+ #[cfg(test)]
167
+ mod tests {
168
+ use super::*;
169
+
170
+ #[test]
171
+ fn test_bundled_library_info_windows() {
172
+ if cfg!(target_os = "windows") {
173
+ let (name, dir) = bundled_library_info();
174
+ assert_eq!(name, "pdfium.dll");
175
+ assert_eq!(dir, "kreuzberg-pdfium");
176
+ }
177
+ }
178
+
179
+ #[test]
180
+ fn test_bundled_library_info_macos() {
181
+ if cfg!(target_os = "macos") {
182
+ let (name, dir) = bundled_library_info();
183
+ assert_eq!(name, "libpdfium.dylib");
184
+ assert_eq!(dir, "kreuzberg-pdfium");
185
+ }
186
+ }
187
+
188
+ #[test]
189
+ fn test_bundled_library_info_linux() {
190
+ if cfg!(target_os = "linux") {
191
+ let (name, dir) = bundled_library_info();
192
+ assert_eq!(name, "libpdfium.so");
193
+ assert_eq!(dir, "kreuzberg-pdfium");
194
+ }
195
+ }
196
+
197
+ #[test]
198
+ fn test_get_extraction_dir() {
199
+ let result = get_extraction_dir();
200
+ assert!(result.is_ok());
201
+ let dir = result.unwrap();
202
+ assert!(dir.to_str().is_some());
203
+ assert!(dir.ends_with("kreuzberg-pdfium"));
204
+ }
205
+
206
+ #[test]
207
+ fn test_is_extracted_library_valid_missing() {
208
+ let nonexistent = PathBuf::from("/tmp/nonexistent-pdfium-test");
209
+ assert!(!is_extracted_library_valid(&nonexistent, 1000));
210
+ }
211
+
212
+ #[test]
213
+ fn test_is_extracted_library_valid_size_match() {
214
+ // Create a temporary test file
215
+ let temp_dir = std::env::temp_dir();
216
+ let test_file = temp_dir.join("test-pdfium-size.dll");
217
+ let test_size = 5_000_000;
218
+ let test_data = vec![0u8; test_size];
219
+
220
+ if let Ok(_) = fs::write(&test_file, &test_data) {
221
+ let is_valid = is_extracted_library_valid(&test_file, test_size);
222
+ assert!(is_valid);
223
+ let _ = fs::remove_file(&test_file);
224
+ }
225
+ }
226
+
227
+ #[test]
228
+ fn test_is_extracted_library_valid_size_tolerance() {
229
+ // Create a temporary test file
230
+ let temp_dir = std::env::temp_dir();
231
+ let test_file = temp_dir.join("test-pdfium-tolerance.dll");
232
+ let original_size = 10_000_000;
233
+ let tolerance = (original_size as f64 * 0.01) as usize;
234
+
235
+ // Create file that's 0.5% smaller (within tolerance)
236
+ let actual_size = original_size - tolerance / 2;
237
+ let test_data = vec![0u8; actual_size];
238
+
239
+ if let Ok(_) = fs::write(&test_file, &test_data) {
240
+ let is_valid = is_extracted_library_valid(&test_file, original_size);
241
+ assert!(is_valid);
242
+ let _ = fs::remove_file(&test_file);
243
+ }
244
+ }
245
+
246
+ #[test]
247
+ fn test_is_extracted_library_valid_size_mismatch() {
248
+ // Create a temporary test file
249
+ let temp_dir = std::env::temp_dir();
250
+ let test_file = temp_dir.join("test-pdfium-mismatch.dll");
251
+ let original_size = 10_000_000;
252
+
253
+ // Create file that's 10% smaller (outside tolerance)
254
+ let actual_size = (original_size as f64 * 0.85) as usize;
255
+ let test_data = vec![0u8; actual_size];
256
+
257
+ if let Ok(_) = fs::write(&test_file, &test_data) {
258
+ let is_valid = is_extracted_library_valid(&test_file, original_size);
259
+ assert!(!is_valid);
260
+ let _ = fs::remove_file(&test_file);
261
+ }
262
+ }
263
+
264
+ #[test]
265
+ #[cfg(feature = "pdf-bundled")]
266
+ fn test_extract_bundled_pdfium() {
267
+ let result = extract_bundled_pdfium();
268
+ assert!(result.is_ok());
269
+
270
+ let lib_path = result.unwrap();
271
+ assert!(
272
+ lib_path.exists(),
273
+ "Extracted library should exist at: {}",
274
+ lib_path.display()
275
+ );
276
+ assert!(lib_path.file_name().is_some(), "Library path should have filename");
277
+
278
+ // Verify correct library name for platform
279
+ let (expected_name, _) = bundled_library_info();
280
+ assert_eq!(lib_path.file_name().unwrap(), expected_name);
281
+ }
282
+
283
+ #[test]
284
+ #[cfg(feature = "pdf-bundled")]
285
+ fn test_extract_bundled_pdfium_reuses_existing() {
286
+ // First extraction
287
+ let result1 = extract_bundled_pdfium();
288
+ assert!(result1.is_ok());
289
+ let path1 = result1.unwrap();
290
+
291
+ // Get file size and basic metadata of first extraction
292
+ let metadata1 = fs::metadata(&path1).expect("Should be able to read metadata");
293
+ let size1 = metadata1.len();
294
+
295
+ // Second extraction should reuse the file
296
+ let result2 = extract_bundled_pdfium();
297
+ assert!(result2.is_ok());
298
+ let path2 = result2.unwrap();
299
+
300
+ // Paths should be identical
301
+ assert_eq!(path1, path2, "Extraction should return same path on second call");
302
+
303
+ // File size should be identical (reused, not rewritten)
304
+ let metadata2 = fs::metadata(&path2).expect("Should be able to read metadata");
305
+ let size2 = metadata2.len();
306
+ assert_eq!(size1, size2, "Reused library should have same file size");
307
+ }
308
+
309
+ #[test]
310
+ #[cfg(unix)]
311
+ #[cfg(feature = "pdf-bundled")]
312
+ fn test_extract_bundled_pdfium_permissions() {
313
+ let result = extract_bundled_pdfium();
314
+ assert!(result.is_ok());
315
+
316
+ let lib_path = result.unwrap();
317
+ let metadata = fs::metadata(&lib_path).expect("Should be able to read metadata");
318
+ let perms = metadata.permissions();
319
+ let mode = perms.mode();
320
+
321
+ // Verify executable bit is set (at least 0o700 or 0o755)
322
+ assert!(
323
+ mode & 0o111 != 0,
324
+ "Library should have executable bit set, got mode: {:#o}",
325
+ mode
326
+ );
327
+ }
328
+ }
@@ -35,6 +35,8 @@
35
35
  //!
36
36
  //! This module requires the `pdf` feature. The `ocr` feature enables additional
37
37
  //! functionality in the PDF extractor for rendering pages to images.
38
+ #[cfg(all(feature = "pdf", feature = "pdf-bundled"))]
39
+ pub mod bundled;
38
40
  #[cfg(feature = "pdf")]
39
41
  pub mod error;
40
42
  #[cfg(feature = "pdf")]
@@ -48,6 +50,8 @@ pub mod table;
48
50
  #[cfg(feature = "pdf")]
49
51
  pub mod text;
50
52
 
53
+ #[cfg(all(feature = "pdf", feature = "pdf-bundled"))]
54
+ pub use bundled::extract_bundled_pdfium;
51
55
  #[cfg(feature = "pdf")]
52
56
  pub use error::PdfError;
53
57
  #[cfg(feature = "pdf")]