kreuzberg 4.0.0.rc1 → 4.0.0.rc2

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.
Files changed (342) hide show
  1. checksums.yaml +4 -4
  2. data/.gitignore +14 -8
  3. data/.rspec +3 -3
  4. data/.rubocop.yaml +1 -534
  5. data/.rubocop.yml +538 -0
  6. data/Gemfile +8 -9
  7. data/Gemfile.lock +9 -109
  8. data/README.md +426 -421
  9. data/Rakefile +25 -25
  10. data/Steepfile +47 -47
  11. data/examples/async_patterns.rb +341 -340
  12. data/ext/kreuzberg_rb/extconf.rb +45 -35
  13. data/ext/kreuzberg_rb/native/Cargo.lock +6535 -0
  14. data/ext/kreuzberg_rb/native/Cargo.toml +44 -36
  15. data/ext/kreuzberg_rb/native/README.md +425 -425
  16. data/ext/kreuzberg_rb/native/build.rs +15 -17
  17. data/ext/kreuzberg_rb/native/include/ieeefp.h +11 -11
  18. data/ext/kreuzberg_rb/native/include/msvc_compat/strings.h +14 -14
  19. data/ext/kreuzberg_rb/native/include/strings.h +20 -20
  20. data/ext/kreuzberg_rb/native/include/unistd.h +47 -47
  21. data/ext/kreuzberg_rb/native/src/lib.rs +2998 -2939
  22. data/extconf.rb +28 -28
  23. data/kreuzberg.gemspec +148 -105
  24. data/lib/kreuzberg/api_proxy.rb +142 -142
  25. data/lib/kreuzberg/cache_api.rb +46 -45
  26. data/lib/kreuzberg/cli.rb +55 -55
  27. data/lib/kreuzberg/cli_proxy.rb +127 -127
  28. data/lib/kreuzberg/config.rb +691 -684
  29. data/lib/kreuzberg/error_context.rb +32 -0
  30. data/lib/kreuzberg/errors.rb +118 -50
  31. data/lib/kreuzberg/extraction_api.rb +85 -84
  32. data/lib/kreuzberg/mcp_proxy.rb +186 -186
  33. data/lib/kreuzberg/ocr_backend_protocol.rb +113 -113
  34. data/lib/kreuzberg/post_processor_protocol.rb +86 -86
  35. data/lib/kreuzberg/result.rb +216 -216
  36. data/lib/kreuzberg/setup_lib_path.rb +80 -79
  37. data/lib/kreuzberg/validator_protocol.rb +89 -89
  38. data/lib/kreuzberg/version.rb +5 -5
  39. data/lib/kreuzberg.rb +103 -82
  40. data/sig/kreuzberg/internal.rbs +184 -184
  41. data/sig/kreuzberg.rbs +520 -468
  42. data/spec/binding/cache_spec.rb +227 -227
  43. data/spec/binding/cli_proxy_spec.rb +85 -87
  44. data/spec/binding/cli_spec.rb +55 -54
  45. data/spec/binding/config_spec.rb +345 -345
  46. data/spec/binding/config_validation_spec.rb +283 -283
  47. data/spec/binding/error_handling_spec.rb +213 -213
  48. data/spec/binding/errors_spec.rb +66 -66
  49. data/spec/binding/plugins/ocr_backend_spec.rb +307 -307
  50. data/spec/binding/plugins/postprocessor_spec.rb +269 -269
  51. data/spec/binding/plugins/validator_spec.rb +274 -274
  52. data/spec/fixtures/config.toml +39 -39
  53. data/spec/fixtures/config.yaml +41 -42
  54. data/spec/fixtures/invalid_config.toml +4 -4
  55. data/spec/smoke/package_spec.rb +178 -178
  56. data/spec/spec_helper.rb +42 -42
  57. data/vendor/kreuzberg/Cargo.toml +204 -134
  58. data/vendor/kreuzberg/README.md +175 -175
  59. data/vendor/kreuzberg/benches/otel_overhead.rs +48 -0
  60. data/vendor/kreuzberg/build.rs +474 -460
  61. data/vendor/kreuzberg/src/api/error.rs +81 -81
  62. data/vendor/kreuzberg/src/api/handlers.rs +199 -199
  63. data/vendor/kreuzberg/src/api/mod.rs +79 -79
  64. data/vendor/kreuzberg/src/api/server.rs +353 -353
  65. data/vendor/kreuzberg/src/api/types.rs +170 -170
  66. data/vendor/kreuzberg/src/cache/mod.rs +1167 -1143
  67. data/vendor/kreuzberg/src/chunking/mod.rs +677 -677
  68. data/vendor/kreuzberg/src/core/batch_mode.rs +95 -35
  69. data/vendor/kreuzberg/src/core/config.rs +1032 -1032
  70. data/vendor/kreuzberg/src/core/extractor.rs +1024 -903
  71. data/vendor/kreuzberg/src/core/io.rs +329 -327
  72. data/vendor/kreuzberg/src/core/mime.rs +605 -615
  73. data/vendor/kreuzberg/src/core/mod.rs +45 -42
  74. data/vendor/kreuzberg/src/core/pipeline.rs +984 -906
  75. data/vendor/kreuzberg/src/embeddings.rs +432 -323
  76. data/vendor/kreuzberg/src/error.rs +431 -431
  77. data/vendor/kreuzberg/src/extraction/archive.rs +954 -954
  78. data/vendor/kreuzberg/src/extraction/docx.rs +40 -40
  79. data/vendor/kreuzberg/src/extraction/email.rs +854 -854
  80. data/vendor/kreuzberg/src/extraction/excel.rs +688 -688
  81. data/vendor/kreuzberg/src/extraction/html.rs +553 -553
  82. data/vendor/kreuzberg/src/extraction/image.rs +368 -368
  83. data/vendor/kreuzberg/src/extraction/libreoffice.rs +563 -564
  84. data/vendor/kreuzberg/src/extraction/markdown.rs +213 -0
  85. data/vendor/kreuzberg/src/extraction/mod.rs +81 -77
  86. data/vendor/kreuzberg/src/extraction/office_metadata/app_properties.rs +398 -398
  87. data/vendor/kreuzberg/src/extraction/office_metadata/core_properties.rs +247 -247
  88. data/vendor/kreuzberg/src/extraction/office_metadata/custom_properties.rs +240 -240
  89. data/vendor/kreuzberg/src/extraction/office_metadata/mod.rs +130 -128
  90. data/vendor/kreuzberg/src/extraction/office_metadata/odt_properties.rs +287 -0
  91. data/vendor/kreuzberg/src/extraction/pptx.rs +3000 -3000
  92. data/vendor/kreuzberg/src/extraction/structured.rs +490 -490
  93. data/vendor/kreuzberg/src/extraction/table.rs +328 -328
  94. data/vendor/kreuzberg/src/extraction/text.rs +269 -269
  95. data/vendor/kreuzberg/src/extraction/xml.rs +333 -333
  96. data/vendor/kreuzberg/src/extractors/archive.rs +446 -425
  97. data/vendor/kreuzberg/src/extractors/bibtex.rs +469 -0
  98. data/vendor/kreuzberg/src/extractors/docbook.rs +502 -0
  99. data/vendor/kreuzberg/src/extractors/docx.rs +367 -479
  100. data/vendor/kreuzberg/src/extractors/email.rs +143 -129
  101. data/vendor/kreuzberg/src/extractors/epub.rs +707 -0
  102. data/vendor/kreuzberg/src/extractors/excel.rs +343 -344
  103. data/vendor/kreuzberg/src/extractors/fictionbook.rs +491 -0
  104. data/vendor/kreuzberg/src/extractors/fictionbook.rs.backup2 +738 -0
  105. data/vendor/kreuzberg/src/extractors/html.rs +393 -410
  106. data/vendor/kreuzberg/src/extractors/image.rs +198 -195
  107. data/vendor/kreuzberg/src/extractors/jats.rs +1051 -0
  108. data/vendor/kreuzberg/src/extractors/jupyter.rs +367 -0
  109. data/vendor/kreuzberg/src/extractors/latex.rs +652 -0
  110. data/vendor/kreuzberg/src/extractors/markdown.rs +700 -0
  111. data/vendor/kreuzberg/src/extractors/mod.rs +365 -268
  112. data/vendor/kreuzberg/src/extractors/odt.rs +628 -0
  113. data/vendor/kreuzberg/src/extractors/opml.rs +634 -0
  114. data/vendor/kreuzberg/src/extractors/orgmode.rs +528 -0
  115. data/vendor/kreuzberg/src/extractors/pdf.rs +493 -496
  116. data/vendor/kreuzberg/src/extractors/pptx.rs +248 -234
  117. data/vendor/kreuzberg/src/extractors/rst.rs +576 -0
  118. data/vendor/kreuzberg/src/extractors/rtf.rs +810 -0
  119. data/vendor/kreuzberg/src/extractors/security.rs +484 -0
  120. data/vendor/kreuzberg/src/extractors/security_tests.rs +367 -0
  121. data/vendor/kreuzberg/src/extractors/structured.rs +140 -126
  122. data/vendor/kreuzberg/src/extractors/text.rs +260 -242
  123. data/vendor/kreuzberg/src/extractors/typst.rs +650 -0
  124. data/vendor/kreuzberg/src/extractors/xml.rs +135 -128
  125. data/vendor/kreuzberg/src/image/dpi.rs +164 -164
  126. data/vendor/kreuzberg/src/image/mod.rs +6 -6
  127. data/vendor/kreuzberg/src/image/preprocessing.rs +417 -417
  128. data/vendor/kreuzberg/src/image/resize.rs +89 -89
  129. data/vendor/kreuzberg/src/keywords/config.rs +154 -154
  130. data/vendor/kreuzberg/src/keywords/mod.rs +237 -237
  131. data/vendor/kreuzberg/src/keywords/processor.rs +267 -267
  132. data/vendor/kreuzberg/src/keywords/rake.rs +293 -294
  133. data/vendor/kreuzberg/src/keywords/types.rs +68 -68
  134. data/vendor/kreuzberg/src/keywords/yake.rs +163 -163
  135. data/vendor/kreuzberg/src/language_detection/mod.rs +942 -942
  136. data/vendor/kreuzberg/src/lib.rs +105 -102
  137. data/vendor/kreuzberg/src/mcp/mod.rs +32 -32
  138. data/vendor/kreuzberg/src/mcp/server.rs +1968 -1966
  139. data/vendor/kreuzberg/src/ocr/cache.rs +469 -469
  140. data/vendor/kreuzberg/src/ocr/error.rs +37 -37
  141. data/vendor/kreuzberg/src/ocr/hocr.rs +216 -216
  142. data/vendor/kreuzberg/src/ocr/mod.rs +58 -58
  143. data/vendor/kreuzberg/src/ocr/processor.rs +863 -847
  144. data/vendor/kreuzberg/src/ocr/table/mod.rs +4 -4
  145. data/vendor/kreuzberg/src/ocr/table/tsv_parser.rs +144 -144
  146. data/vendor/kreuzberg/src/ocr/tesseract_backend.rs +450 -450
  147. data/vendor/kreuzberg/src/ocr/types.rs +393 -393
  148. data/vendor/kreuzberg/src/ocr/utils.rs +47 -47
  149. data/vendor/kreuzberg/src/ocr/validation.rs +206 -206
  150. data/vendor/kreuzberg/src/panic_context.rs +154 -0
  151. data/vendor/kreuzberg/src/pdf/error.rs +122 -122
  152. data/vendor/kreuzberg/src/pdf/images.rs +139 -139
  153. data/vendor/kreuzberg/src/pdf/metadata.rs +346 -346
  154. data/vendor/kreuzberg/src/pdf/mod.rs +50 -50
  155. data/vendor/kreuzberg/src/pdf/rendering.rs +369 -369
  156. data/vendor/kreuzberg/src/pdf/table.rs +393 -420
  157. data/vendor/kreuzberg/src/pdf/text.rs +158 -161
  158. data/vendor/kreuzberg/src/plugins/extractor.rs +1013 -1010
  159. data/vendor/kreuzberg/src/plugins/mod.rs +209 -209
  160. data/vendor/kreuzberg/src/plugins/ocr.rs +620 -629
  161. data/vendor/kreuzberg/src/plugins/processor.rs +642 -641
  162. data/vendor/kreuzberg/src/plugins/registry.rs +1337 -1324
  163. data/vendor/kreuzberg/src/plugins/traits.rs +258 -258
  164. data/vendor/kreuzberg/src/plugins/validator.rs +956 -955
  165. data/vendor/kreuzberg/src/stopwords/mod.rs +1470 -1470
  166. data/vendor/kreuzberg/src/text/mod.rs +19 -19
  167. data/vendor/kreuzberg/src/text/quality.rs +697 -697
  168. data/vendor/kreuzberg/src/text/string_utils.rs +217 -217
  169. data/vendor/kreuzberg/src/text/token_reduction/cjk_utils.rs +164 -164
  170. data/vendor/kreuzberg/src/text/token_reduction/config.rs +100 -100
  171. data/vendor/kreuzberg/src/text/token_reduction/core.rs +796 -796
  172. data/vendor/kreuzberg/src/text/token_reduction/filters.rs +902 -902
  173. data/vendor/kreuzberg/src/text/token_reduction/mod.rs +160 -160
  174. data/vendor/kreuzberg/src/text/token_reduction/semantic.rs +619 -619
  175. data/vendor/kreuzberg/src/text/token_reduction/simd_text.rs +147 -147
  176. data/vendor/kreuzberg/src/types.rs +903 -873
  177. data/vendor/kreuzberg/src/utils/mod.rs +17 -17
  178. data/vendor/kreuzberg/src/utils/quality.rs +959 -959
  179. data/vendor/kreuzberg/src/utils/string_utils.rs +381 -381
  180. data/vendor/kreuzberg/stopwords/af_stopwords.json +53 -53
  181. data/vendor/kreuzberg/stopwords/ar_stopwords.json +482 -482
  182. data/vendor/kreuzberg/stopwords/bg_stopwords.json +261 -261
  183. data/vendor/kreuzberg/stopwords/bn_stopwords.json +400 -400
  184. data/vendor/kreuzberg/stopwords/br_stopwords.json +1205 -1205
  185. data/vendor/kreuzberg/stopwords/ca_stopwords.json +280 -280
  186. data/vendor/kreuzberg/stopwords/cs_stopwords.json +425 -425
  187. data/vendor/kreuzberg/stopwords/da_stopwords.json +172 -172
  188. data/vendor/kreuzberg/stopwords/de_stopwords.json +622 -622
  189. data/vendor/kreuzberg/stopwords/el_stopwords.json +849 -849
  190. data/vendor/kreuzberg/stopwords/en_stopwords.json +1300 -1300
  191. data/vendor/kreuzberg/stopwords/eo_stopwords.json +175 -175
  192. data/vendor/kreuzberg/stopwords/es_stopwords.json +734 -734
  193. data/vendor/kreuzberg/stopwords/et_stopwords.json +37 -37
  194. data/vendor/kreuzberg/stopwords/eu_stopwords.json +100 -100
  195. data/vendor/kreuzberg/stopwords/fa_stopwords.json +801 -801
  196. data/vendor/kreuzberg/stopwords/fi_stopwords.json +849 -849
  197. data/vendor/kreuzberg/stopwords/fr_stopwords.json +693 -693
  198. data/vendor/kreuzberg/stopwords/ga_stopwords.json +111 -111
  199. data/vendor/kreuzberg/stopwords/gl_stopwords.json +162 -162
  200. data/vendor/kreuzberg/stopwords/gu_stopwords.json +226 -226
  201. data/vendor/kreuzberg/stopwords/ha_stopwords.json +41 -41
  202. data/vendor/kreuzberg/stopwords/he_stopwords.json +196 -196
  203. data/vendor/kreuzberg/stopwords/hi_stopwords.json +227 -227
  204. data/vendor/kreuzberg/stopwords/hr_stopwords.json +181 -181
  205. data/vendor/kreuzberg/stopwords/hu_stopwords.json +791 -791
  206. data/vendor/kreuzberg/stopwords/hy_stopwords.json +47 -47
  207. data/vendor/kreuzberg/stopwords/id_stopwords.json +760 -760
  208. data/vendor/kreuzberg/stopwords/it_stopwords.json +634 -634
  209. data/vendor/kreuzberg/stopwords/ja_stopwords.json +136 -136
  210. data/vendor/kreuzberg/stopwords/kn_stopwords.json +84 -84
  211. data/vendor/kreuzberg/stopwords/ko_stopwords.json +681 -681
  212. data/vendor/kreuzberg/stopwords/ku_stopwords.json +64 -64
  213. data/vendor/kreuzberg/stopwords/la_stopwords.json +51 -51
  214. data/vendor/kreuzberg/stopwords/lt_stopwords.json +476 -476
  215. data/vendor/kreuzberg/stopwords/lv_stopwords.json +163 -163
  216. data/vendor/kreuzberg/stopwords/ml_stopwords.json +1 -1
  217. data/vendor/kreuzberg/stopwords/mr_stopwords.json +101 -101
  218. data/vendor/kreuzberg/stopwords/ms_stopwords.json +477 -477
  219. data/vendor/kreuzberg/stopwords/ne_stopwords.json +490 -490
  220. data/vendor/kreuzberg/stopwords/nl_stopwords.json +415 -415
  221. data/vendor/kreuzberg/stopwords/no_stopwords.json +223 -223
  222. data/vendor/kreuzberg/stopwords/pl_stopwords.json +331 -331
  223. data/vendor/kreuzberg/stopwords/pt_stopwords.json +562 -562
  224. data/vendor/kreuzberg/stopwords/ro_stopwords.json +436 -436
  225. data/vendor/kreuzberg/stopwords/ru_stopwords.json +561 -561
  226. data/vendor/kreuzberg/stopwords/si_stopwords.json +193 -193
  227. data/vendor/kreuzberg/stopwords/sk_stopwords.json +420 -420
  228. data/vendor/kreuzberg/stopwords/sl_stopwords.json +448 -448
  229. data/vendor/kreuzberg/stopwords/so_stopwords.json +32 -32
  230. data/vendor/kreuzberg/stopwords/st_stopwords.json +33 -33
  231. data/vendor/kreuzberg/stopwords/sv_stopwords.json +420 -420
  232. data/vendor/kreuzberg/stopwords/sw_stopwords.json +76 -76
  233. data/vendor/kreuzberg/stopwords/ta_stopwords.json +129 -129
  234. data/vendor/kreuzberg/stopwords/te_stopwords.json +54 -54
  235. data/vendor/kreuzberg/stopwords/th_stopwords.json +118 -118
  236. data/vendor/kreuzberg/stopwords/tl_stopwords.json +149 -149
  237. data/vendor/kreuzberg/stopwords/tr_stopwords.json +506 -506
  238. data/vendor/kreuzberg/stopwords/uk_stopwords.json +75 -75
  239. data/vendor/kreuzberg/stopwords/ur_stopwords.json +519 -519
  240. data/vendor/kreuzberg/stopwords/vi_stopwords.json +647 -647
  241. data/vendor/kreuzberg/stopwords/yo_stopwords.json +62 -62
  242. data/vendor/kreuzberg/stopwords/zh_stopwords.json +796 -796
  243. data/vendor/kreuzberg/stopwords/zu_stopwords.json +31 -31
  244. data/vendor/kreuzberg/tests/api_extract_multipart.rs +52 -0
  245. data/vendor/kreuzberg/tests/api_tests.rs +966 -966
  246. data/vendor/kreuzberg/tests/archive_integration.rs +543 -543
  247. data/vendor/kreuzberg/tests/batch_orchestration.rs +556 -542
  248. data/vendor/kreuzberg/tests/batch_processing.rs +316 -304
  249. data/vendor/kreuzberg/tests/bibtex_parity_test.rs +421 -0
  250. data/vendor/kreuzberg/tests/concurrency_stress.rs +525 -509
  251. data/vendor/kreuzberg/tests/config_features.rs +598 -580
  252. data/vendor/kreuzberg/tests/config_loading_tests.rs +415 -439
  253. data/vendor/kreuzberg/tests/core_integration.rs +510 -493
  254. data/vendor/kreuzberg/tests/csv_integration.rs +414 -424
  255. data/vendor/kreuzberg/tests/docbook_extractor_tests.rs +498 -0
  256. data/vendor/kreuzberg/tests/docx_metadata_extraction_test.rs +122 -124
  257. data/vendor/kreuzberg/tests/docx_vs_pandoc_comparison.rs +370 -0
  258. data/vendor/kreuzberg/tests/email_integration.rs +325 -325
  259. data/vendor/kreuzberg/tests/epub_native_extractor_tests.rs +275 -0
  260. data/vendor/kreuzberg/tests/error_handling.rs +393 -393
  261. data/vendor/kreuzberg/tests/fictionbook_extractor_tests.rs +228 -0
  262. data/vendor/kreuzberg/tests/format_integration.rs +159 -159
  263. data/vendor/kreuzberg/tests/helpers/mod.rs +142 -142
  264. data/vendor/kreuzberg/tests/html_table_test.rs +551 -0
  265. data/vendor/kreuzberg/tests/image_integration.rs +253 -253
  266. data/vendor/kreuzberg/tests/instrumentation_test.rs +139 -0
  267. data/vendor/kreuzberg/tests/jats_extractor_tests.rs +639 -0
  268. data/vendor/kreuzberg/tests/jupyter_extractor_tests.rs +704 -0
  269. data/vendor/kreuzberg/tests/keywords_integration.rs +479 -479
  270. data/vendor/kreuzberg/tests/keywords_quality.rs +509 -509
  271. data/vendor/kreuzberg/tests/latex_extractor_tests.rs +496 -0
  272. data/vendor/kreuzberg/tests/markdown_extractor_tests.rs +490 -0
  273. data/vendor/kreuzberg/tests/mime_detection.rs +428 -428
  274. data/vendor/kreuzberg/tests/ocr_configuration.rs +510 -510
  275. data/vendor/kreuzberg/tests/ocr_errors.rs +676 -676
  276. data/vendor/kreuzberg/tests/ocr_quality.rs +627 -627
  277. data/vendor/kreuzberg/tests/ocr_stress.rs +469 -469
  278. data/vendor/kreuzberg/tests/odt_extractor_tests.rs +695 -0
  279. data/vendor/kreuzberg/tests/opml_extractor_tests.rs +616 -0
  280. data/vendor/kreuzberg/tests/orgmode_extractor_tests.rs +822 -0
  281. data/vendor/kreuzberg/tests/pdf_integration.rs +43 -43
  282. data/vendor/kreuzberg/tests/pipeline_integration.rs +1411 -1412
  283. data/vendor/kreuzberg/tests/plugin_ocr_backend_test.rs +771 -771
  284. data/vendor/kreuzberg/tests/plugin_postprocessor_test.rs +560 -561
  285. data/vendor/kreuzberg/tests/plugin_system.rs +921 -921
  286. data/vendor/kreuzberg/tests/plugin_validator_test.rs +783 -783
  287. data/vendor/kreuzberg/tests/registry_integration_tests.rs +586 -607
  288. data/vendor/kreuzberg/tests/rst_extractor_tests.rs +692 -0
  289. data/vendor/kreuzberg/tests/rtf_extractor_tests.rs +776 -0
  290. data/vendor/kreuzberg/tests/security_validation.rs +415 -404
  291. data/vendor/kreuzberg/tests/stopwords_integration_test.rs +888 -888
  292. data/vendor/kreuzberg/tests/test_fastembed.rs +609 -609
  293. data/vendor/kreuzberg/tests/typst_behavioral_tests.rs +1259 -0
  294. data/vendor/kreuzberg/tests/typst_extractor_tests.rs +647 -0
  295. data/vendor/kreuzberg/tests/xlsx_metadata_extraction_test.rs +87 -87
  296. data/vendor/rb-sys/.cargo-ok +1 -0
  297. data/vendor/rb-sys/.cargo_vcs_info.json +6 -0
  298. data/vendor/rb-sys/Cargo.lock +393 -0
  299. data/vendor/rb-sys/Cargo.toml +70 -0
  300. data/vendor/rb-sys/Cargo.toml.orig +57 -0
  301. data/vendor/rb-sys/LICENSE-APACHE +190 -0
  302. data/vendor/rb-sys/LICENSE-MIT +21 -0
  303. data/vendor/rb-sys/bin/release.sh +21 -0
  304. data/vendor/rb-sys/build/features.rs +108 -0
  305. data/vendor/rb-sys/build/main.rs +246 -0
  306. data/vendor/rb-sys/build/stable_api_config.rs +153 -0
  307. data/vendor/rb-sys/build/version.rs +48 -0
  308. data/vendor/rb-sys/readme.md +36 -0
  309. data/vendor/rb-sys/src/bindings.rs +21 -0
  310. data/vendor/rb-sys/src/hidden.rs +11 -0
  311. data/vendor/rb-sys/src/lib.rs +34 -0
  312. data/vendor/rb-sys/src/macros.rs +371 -0
  313. data/vendor/rb-sys/src/memory.rs +53 -0
  314. data/vendor/rb-sys/src/ruby_abi_version.rs +38 -0
  315. data/vendor/rb-sys/src/special_consts.rs +31 -0
  316. data/vendor/rb-sys/src/stable_api/compiled.c +179 -0
  317. data/vendor/rb-sys/src/stable_api/compiled.rs +257 -0
  318. data/vendor/rb-sys/src/stable_api/ruby_2_6.rs +316 -0
  319. data/vendor/rb-sys/src/stable_api/ruby_2_7.rs +316 -0
  320. data/vendor/rb-sys/src/stable_api/ruby_3_0.rs +324 -0
  321. data/vendor/rb-sys/src/stable_api/ruby_3_1.rs +317 -0
  322. data/vendor/rb-sys/src/stable_api/ruby_3_2.rs +315 -0
  323. data/vendor/rb-sys/src/stable_api/ruby_3_3.rs +326 -0
  324. data/vendor/rb-sys/src/stable_api/ruby_3_4.rs +327 -0
  325. data/vendor/rb-sys/src/stable_api.rs +261 -0
  326. data/vendor/rb-sys/src/symbol.rs +31 -0
  327. data/vendor/rb-sys/src/tracking_allocator.rs +332 -0
  328. data/vendor/rb-sys/src/utils.rs +89 -0
  329. data/vendor/rb-sys/src/value_type.rs +7 -0
  330. metadata +90 -95
  331. data/pkg/kreuzberg-4.0.0.rc1.gem +0 -0
  332. data/spec/examples.txt +0 -104
  333. data/vendor/kreuzberg/src/bin/profile_extract.rs +0 -455
  334. data/vendor/kreuzberg/src/extraction/pandoc/batch.rs +0 -275
  335. data/vendor/kreuzberg/src/extraction/pandoc/mime_types.rs +0 -178
  336. data/vendor/kreuzberg/src/extraction/pandoc/mod.rs +0 -491
  337. data/vendor/kreuzberg/src/extraction/pandoc/server.rs +0 -496
  338. data/vendor/kreuzberg/src/extraction/pandoc/subprocess.rs +0 -1188
  339. data/vendor/kreuzberg/src/extraction/pandoc/version.rs +0 -162
  340. data/vendor/kreuzberg/src/extractors/pandoc.rs +0 -201
  341. data/vendor/kreuzberg/tests/chunking_offset_demo.rs +0 -92
  342. data/vendor/kreuzberg/tests/pandoc_integration.rs +0 -503
@@ -1,1966 +1,1968 @@
1
- //! MCP server implementation for Kreuzberg.
2
- //!
3
- //! This module provides the core MCP server that exposes document extraction
4
- //! as tools for AI assistants via the Model Context Protocol.
5
-
6
- use base64::prelude::*;
7
- use rmcp::{
8
- ErrorData as McpError, ServerHandler, ServiceExt,
9
- handler::server::{router::tool::ToolRouter, wrapper::Parameters},
10
- model::*,
11
- schemars, tool, tool_handler, tool_router,
12
- transport::stdio,
13
- };
14
-
15
- use crate::{
16
- ExtractionConfig, ExtractionResult as KreuzbergResult, KreuzbergError, batch_extract_file, batch_extract_file_sync,
17
- cache, detect_mime_type, extract_bytes, extract_bytes_sync, extract_file, extract_file_sync,
18
- };
19
-
20
- /// Request parameters for file extraction.
21
- #[derive(Debug, serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
22
- pub struct ExtractFileParams {
23
- /// Path to the file to extract
24
- pub path: String,
25
- /// Optional MIME type hint (auto-detected if not provided)
26
- #[serde(skip_serializing_if = "Option::is_none")]
27
- pub mime_type: Option<String>,
28
- /// Enable OCR for scanned documents
29
- #[serde(default)]
30
- pub enable_ocr: bool,
31
- /// Force OCR even if text extraction succeeds
32
- #[serde(default)]
33
- pub force_ocr: bool,
34
- /// Use async extraction (default: false for sync)
35
- #[serde(default)]
36
- pub r#async: bool,
37
- }
38
-
39
- /// Request parameters for bytes extraction.
40
- #[derive(Debug, serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
41
- pub struct ExtractBytesParams {
42
- /// Base64-encoded file content
43
- pub data: String,
44
- /// Optional MIME type hint (auto-detected if not provided)
45
- #[serde(skip_serializing_if = "Option::is_none")]
46
- pub mime_type: Option<String>,
47
- /// Enable OCR for scanned documents
48
- #[serde(default)]
49
- pub enable_ocr: bool,
50
- /// Force OCR even if text extraction succeeds
51
- #[serde(default)]
52
- pub force_ocr: bool,
53
- /// Use async extraction (default: false for sync)
54
- #[serde(default)]
55
- pub r#async: bool,
56
- }
57
-
58
- /// Request parameters for batch file extraction.
59
- #[derive(Debug, serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
60
- pub struct BatchExtractFilesParams {
61
- /// Paths to files to extract
62
- pub paths: Vec<String>,
63
- /// Enable OCR for scanned documents
64
- #[serde(default)]
65
- pub enable_ocr: bool,
66
- /// Force OCR even if text extraction succeeds
67
- #[serde(default)]
68
- pub force_ocr: bool,
69
- /// Use async extraction (default: false for sync)
70
- #[serde(default)]
71
- pub r#async: bool,
72
- }
73
-
74
- /// Request parameters for MIME type detection.
75
- #[derive(Debug, serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
76
- pub struct DetectMimeTypeParams {
77
- /// Path to the file
78
- pub path: String,
79
- /// Use content-based detection (default: true)
80
- #[serde(default = "default_use_content")]
81
- pub use_content: bool,
82
- }
83
-
84
- fn default_use_content() -> bool {
85
- true
86
- }
87
-
88
- /// Map Kreuzberg errors to MCP error responses with appropriate error codes.
89
- ///
90
- /// This function ensures different error types are properly differentiated in MCP responses:
91
- /// - `Validation` errors → `INVALID_PARAMS` (-32602)
92
- /// - `UnsupportedFormat` errors → `INVALID_PARAMS` (-32602)
93
- /// - `Parsing` errors → `PARSE_ERROR` (-32700)
94
- /// - `Io` errors → `INTERNAL_ERROR` (-32603) with context preserved
95
- /// - All other errors → `INTERNAL_ERROR` (-32603)
96
- ///
97
- /// The error message and source chain are preserved to aid debugging.
98
- #[doc(hidden)]
99
- pub fn map_kreuzberg_error_to_mcp(error: KreuzbergError) -> McpError {
100
- match error {
101
- KreuzbergError::Validation { message, source } => {
102
- let mut error_message = format!("Validation error: {}", message);
103
- if let Some(src) = source {
104
- error_message.push_str(&format!(" (caused by: {})", src));
105
- }
106
- McpError::invalid_params(error_message, None)
107
- }
108
-
109
- KreuzbergError::UnsupportedFormat(mime_type) => {
110
- McpError::invalid_params(format!("Unsupported format: {}", mime_type), None)
111
- }
112
-
113
- KreuzbergError::MissingDependency(dep) => McpError::invalid_params(
114
- format!(
115
- "Missing required dependency: {}. Please install it to use this feature.",
116
- dep
117
- ),
118
- None,
119
- ),
120
-
121
- KreuzbergError::Parsing { message, source } => {
122
- let mut error_message = format!("Parsing error: {}", message);
123
- if let Some(src) = source {
124
- error_message.push_str(&format!(" (caused by: {})", src));
125
- }
126
- McpError::parse_error(error_message, None)
127
- }
128
-
129
- // OSError/RuntimeError must bubble up - system errors need user reports ~keep
130
- KreuzbergError::Io(io_err) => McpError::internal_error(format!("System I/O error: {}", io_err), None),
131
-
132
- KreuzbergError::Ocr { message, source } => {
133
- let mut error_message = format!("OCR processing error: {}", message);
134
- if let Some(src) = source {
135
- error_message.push_str(&format!(" (caused by: {})", src));
136
- }
137
- McpError::internal_error(error_message, None)
138
- }
139
-
140
- KreuzbergError::Cache { message, source } => {
141
- let mut error_message = format!("Cache error: {}", message);
142
- if let Some(src) = source {
143
- error_message.push_str(&format!(" (caused by: {})", src));
144
- }
145
- McpError::internal_error(error_message, None)
146
- }
147
-
148
- KreuzbergError::ImageProcessing { message, source } => {
149
- let mut error_message = format!("Image processing error: {}", message);
150
- if let Some(src) = source {
151
- error_message.push_str(&format!(" (caused by: {})", src));
152
- }
153
- McpError::internal_error(error_message, None)
154
- }
155
-
156
- KreuzbergError::Serialization { message, source } => {
157
- let mut error_message = format!("Serialization error: {}", message);
158
- if let Some(src) = source {
159
- error_message.push_str(&format!(" (caused by: {})", src));
160
- }
161
- McpError::internal_error(error_message, None)
162
- }
163
-
164
- KreuzbergError::Plugin { message, plugin_name } => {
165
- McpError::internal_error(format!("Plugin '{}' error: {}", plugin_name, message), None)
166
- }
167
-
168
- KreuzbergError::LockPoisoned(msg) => McpError::internal_error(format!("Internal lock poisoned: {}", msg), None),
169
-
170
- KreuzbergError::Other(msg) => McpError::internal_error(msg, None),
171
- }
172
- }
173
-
174
- /// Kreuzberg MCP server.
175
- ///
176
- /// Provides document extraction capabilities via MCP tools.
177
- ///
178
- /// The server loads a default extraction configuration from kreuzberg.toml/yaml/json
179
- /// via discovery. Per-request OCR settings override the defaults.
180
- #[derive(Clone)]
181
- pub struct KreuzbergMcp {
182
- tool_router: ToolRouter<KreuzbergMcp>,
183
- /// Default extraction configuration loaded from config file via discovery
184
- default_config: std::sync::Arc<ExtractionConfig>,
185
- }
186
-
187
- #[tool_router]
188
- impl KreuzbergMcp {
189
- /// Create a new Kreuzberg MCP server instance with default config.
190
- ///
191
- /// Uses `ExtractionConfig::discover()` to search for kreuzberg.toml/yaml/json
192
- /// in current and parent directories. Falls back to default configuration if
193
- /// no config file is found.
194
- #[allow(clippy::manual_unwrap_or_default)]
195
- pub fn new() -> crate::Result<Self> {
196
- let config = match ExtractionConfig::discover()? {
197
- Some(config) => {
198
- #[cfg(feature = "api")]
199
- tracing::info!("Loaded extraction config from discovered file");
200
- config
201
- }
202
- None => {
203
- #[cfg(feature = "api")]
204
- tracing::info!("No config file found, using default configuration");
205
- ExtractionConfig::default()
206
- }
207
- };
208
-
209
- Ok(Self::with_config(config))
210
- }
211
-
212
- /// Create a new Kreuzberg MCP server instance with explicit config.
213
- ///
214
- /// # Arguments
215
- ///
216
- /// * `config` - Default extraction configuration for all tool calls
217
- pub fn with_config(config: ExtractionConfig) -> Self {
218
- Self {
219
- tool_router: Self::tool_router(),
220
- default_config: std::sync::Arc::new(config),
221
- }
222
- }
223
-
224
- /// Extract content from a file.
225
- ///
226
- /// This tool extracts text, metadata, and tables from documents in various formats
227
- /// including PDFs, Word documents, Excel spreadsheets, images (with OCR), and more.
228
- #[tool(
229
- description = "Extract content from a file by path. Supports PDFs, Word, Excel, images (with OCR), HTML, and more."
230
- )]
231
- async fn extract_file(
232
- &self,
233
- Parameters(params): Parameters<ExtractFileParams>,
234
- ) -> Result<CallToolResult, McpError> {
235
- let config = build_config(&self.default_config, params.enable_ocr, params.force_ocr);
236
-
237
- let result = if params.r#async {
238
- extract_file(&params.path, params.mime_type.as_deref(), &config)
239
- .await
240
- .map_err(map_kreuzberg_error_to_mcp)?
241
- } else {
242
- extract_file_sync(&params.path, params.mime_type.as_deref(), &config).map_err(map_kreuzberg_error_to_mcp)?
243
- };
244
-
245
- let response = format_extraction_result(&result);
246
- Ok(CallToolResult::success(vec![Content::text(response)]))
247
- }
248
-
249
- /// Extract content from base64-encoded bytes.
250
- ///
251
- /// This tool extracts text, metadata, and tables from base64-encoded document data.
252
- #[tool(
253
- description = "Extract content from base64-encoded file data. Returns extracted text, metadata, and tables."
254
- )]
255
- async fn extract_bytes(
256
- &self,
257
- Parameters(params): Parameters<ExtractBytesParams>,
258
- ) -> Result<CallToolResult, McpError> {
259
- let bytes = BASE64_STANDARD
260
- .decode(&params.data)
261
- .map_err(|e| McpError::invalid_params(format!("Invalid base64: {}", e), None))?;
262
-
263
- let config = build_config(&self.default_config, params.enable_ocr, params.force_ocr);
264
-
265
- let mime_type = params.mime_type.as_deref().unwrap_or("");
266
-
267
- let result = if params.r#async {
268
- extract_bytes(&bytes, mime_type, &config)
269
- .await
270
- .map_err(map_kreuzberg_error_to_mcp)?
271
- } else {
272
- extract_bytes_sync(&bytes, mime_type, &config).map_err(map_kreuzberg_error_to_mcp)?
273
- };
274
-
275
- let response = format_extraction_result(&result);
276
- Ok(CallToolResult::success(vec![Content::text(response)]))
277
- }
278
-
279
- /// Extract content from multiple files in parallel.
280
- ///
281
- /// This tool efficiently processes multiple documents simultaneously, useful for batch operations.
282
- #[tool(description = "Extract content from multiple files in parallel. Returns results for all files.")]
283
- async fn batch_extract_files(
284
- &self,
285
- Parameters(params): Parameters<BatchExtractFilesParams>,
286
- ) -> Result<CallToolResult, McpError> {
287
- let config = build_config(&self.default_config, params.enable_ocr, params.force_ocr);
288
-
289
- let results = if params.r#async {
290
- batch_extract_file(params.paths.clone(), &config)
291
- .await
292
- .map_err(map_kreuzberg_error_to_mcp)?
293
- } else {
294
- batch_extract_file_sync(params.paths.clone(), &config).map_err(map_kreuzberg_error_to_mcp)?
295
- };
296
-
297
- let mut response = String::new();
298
- for (i, result) in results.iter().enumerate() {
299
- response.push_str(&format!("=== Document {}: {} ===\n", i + 1, params.paths[i]));
300
- response.push_str(&format_extraction_result(result));
301
- response.push_str("\n\n");
302
- }
303
-
304
- Ok(CallToolResult::success(vec![Content::text(response)]))
305
- }
306
-
307
- /// Detect the MIME type of a file.
308
- ///
309
- /// This tool identifies the file format, useful for determining which extractor to use.
310
- #[tool(description = "Detect the MIME type of a file. Returns the detected MIME type string.")]
311
- fn detect_mime_type(
312
- &self,
313
- Parameters(params): Parameters<DetectMimeTypeParams>,
314
- ) -> Result<CallToolResult, McpError> {
315
- let mime_type = detect_mime_type(&params.path, params.use_content).map_err(map_kreuzberg_error_to_mcp)?;
316
-
317
- Ok(CallToolResult::success(vec![Content::text(mime_type)]))
318
- }
319
-
320
- /// Get cache statistics.
321
- ///
322
- /// This tool returns statistics about the cache including total files, size, and disk space.
323
- #[tool(description = "Get cache statistics including total files, size, and available disk space.")]
324
- fn cache_stats(&self, Parameters(_): Parameters<()>) -> Result<CallToolResult, McpError> {
325
- let cache_dir = std::env::current_dir()
326
- .unwrap_or_else(|_| std::path::PathBuf::from("."))
327
- .join(".kreuzberg");
328
-
329
- let stats = cache::get_cache_metadata(cache_dir.to_str().unwrap_or(".")).map_err(map_kreuzberg_error_to_mcp)?;
330
-
331
- let response = format!(
332
- "Cache Statistics\n\
333
- ================\n\
334
- Directory: {}\n\
335
- Total files: {}\n\
336
- Total size: {:.2} MB\n\
337
- Available space: {:.2} MB\n\
338
- Oldest file age: {:.2} days\n\
339
- Newest file age: {:.2} days",
340
- cache_dir.to_string_lossy(),
341
- stats.total_files,
342
- stats.total_size_mb,
343
- stats.available_space_mb,
344
- stats.oldest_file_age_days,
345
- stats.newest_file_age_days
346
- );
347
-
348
- Ok(CallToolResult::success(vec![Content::text(response)]))
349
- }
350
-
351
- /// Clear the cache.
352
- ///
353
- /// This tool removes all cached files and returns the number of files removed and space freed.
354
- #[tool(description = "Clear all cached files. Returns the number of files removed and space freed in MB.")]
355
- fn cache_clear(&self, Parameters(_): Parameters<()>) -> Result<CallToolResult, McpError> {
356
- let cache_dir = std::env::current_dir()
357
- .unwrap_or_else(|_| std::path::PathBuf::from("."))
358
- .join(".kreuzberg");
359
-
360
- let (removed_files, freed_mb) =
361
- cache::clear_cache_directory(cache_dir.to_str().unwrap_or(".")).map_err(map_kreuzberg_error_to_mcp)?;
362
-
363
- let response = format!(
364
- "Cache cleared successfully\n\
365
- Directory: {}\n\
366
- Removed files: {}\n\
367
- Freed space: {:.2} MB",
368
- cache_dir.to_string_lossy(),
369
- removed_files,
370
- freed_mb
371
- );
372
-
373
- Ok(CallToolResult::success(vec![Content::text(response)]))
374
- }
375
- }
376
-
377
- #[tool_handler]
378
- impl ServerHandler for KreuzbergMcp {
379
- fn get_info(&self) -> ServerInfo {
380
- ServerInfo {
381
- protocol_version: ProtocolVersion::default(),
382
- capabilities: ServerCapabilities {
383
- tools: Some(ToolsCapability::default()),
384
- ..Default::default()
385
- },
386
- server_info: Implementation {
387
- name: "kreuzberg-mcp".to_string(),
388
- title: Some("Kreuzberg Document Intelligence MCP Server".to_string()),
389
- version: env!("CARGO_PKG_VERSION").to_string(),
390
- icons: None,
391
- website_url: Some("https://goldziher.github.io/kreuzberg/".to_string()),
392
- },
393
- instructions: Some(
394
- "Extract content from documents in various formats. Supports PDFs, Word documents, \
395
- Excel spreadsheets, images (with OCR), HTML, emails, and more. Use enable_ocr=true \
396
- for scanned documents, force_ocr=true to always use OCR even if text extraction \
397
- succeeds."
398
- .to_string(),
399
- ),
400
- }
401
- }
402
- }
403
-
404
- impl Default for KreuzbergMcp {
405
- fn default() -> Self {
406
- Self::new().unwrap_or_else(|e| {
407
- #[cfg(feature = "api")]
408
- tracing::warn!("Failed to discover config, using default: {}", e);
409
- #[cfg(not(feature = "api"))]
410
- tracing::debug!("Warning: Failed to discover config, using default: {}", e);
411
- Self::with_config(ExtractionConfig::default())
412
- })
413
- }
414
- }
415
-
416
- /// Start the Kreuzberg MCP server.
417
- ///
418
- /// This function initializes and runs the MCP server using stdio transport.
419
- /// It will block until the server is shut down.
420
- ///
421
- /// # Errors
422
- ///
423
- /// Returns an error if the server fails to start or encounters a fatal error.
424
- ///
425
- /// # Example
426
- ///
427
- /// ```rust,no_run
428
- /// use kreuzberg::mcp::start_mcp_server;
429
- ///
430
- /// #[tokio::main]
431
- /// async fn main() -> anyhow::Result<()> {
432
- /// start_mcp_server().await?;
433
- /// Ok(())
434
- /// }
435
- /// ```
436
- pub async fn start_mcp_server() -> Result<(), Box<dyn std::error::Error>> {
437
- let service = KreuzbergMcp::new()?.serve(stdio()).await?;
438
-
439
- service.waiting().await?;
440
- Ok(())
441
- }
442
-
443
- /// Start MCP server with custom extraction config.
444
- ///
445
- /// This variant allows specifying a custom extraction configuration
446
- /// (e.g., loaded from a file) instead of using defaults.
447
- pub async fn start_mcp_server_with_config(config: ExtractionConfig) -> Result<(), Box<dyn std::error::Error>> {
448
- let service = KreuzbergMcp::with_config(config).serve(stdio()).await?;
449
-
450
- service.waiting().await?;
451
- Ok(())
452
- }
453
-
454
- /// Build extraction config from MCP parameters.
455
- ///
456
- /// Starts with the default config and overlays OCR settings from request parameters.
457
- fn build_config(default_config: &ExtractionConfig, enable_ocr: bool, force_ocr: bool) -> ExtractionConfig {
458
- let mut config = default_config.clone();
459
-
460
- config.ocr = if enable_ocr {
461
- Some(crate::OcrConfig {
462
- backend: "tesseract".to_string(),
463
- language: "eng".to_string(),
464
- tesseract_config: None,
465
- })
466
- } else {
467
- None
468
- };
469
- config.force_ocr = force_ocr;
470
-
471
- config
472
- }
473
-
474
- /// Format extraction result as human-readable text.
475
- fn format_extraction_result(result: &KreuzbergResult) -> String {
476
- let mut response = String::new();
477
-
478
- response.push_str(&format!("Content ({} characters):\n", result.content.len()));
479
- response.push_str(&result.content);
480
- response.push_str("\n\n");
481
-
482
- response.push_str("Metadata:\n");
483
- response.push_str(&serde_json::to_string_pretty(&result.metadata).unwrap_or_default());
484
- response.push_str("\n\n");
485
-
486
- if !result.tables.is_empty() {
487
- response.push_str(&format!("Tables ({}):\n", result.tables.len()));
488
- for (i, table) in result.tables.iter().enumerate() {
489
- response.push_str(&format!("\nTable {} (page {}):\n", i + 1, table.page_number));
490
- response.push_str(&table.markdown);
491
- response.push('\n');
492
- }
493
- }
494
-
495
- response
496
- }
497
-
498
- #[cfg(test)]
499
- mod tests {
500
- use super::*;
501
- use std::path::PathBuf;
502
-
503
- /// Get the path to a test document relative to workspace root.
504
- fn get_test_path(relative_path: &str) -> String {
505
- let workspace_root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
506
- .parent()
507
- .unwrap()
508
- .parent()
509
- .unwrap()
510
- .to_path_buf();
511
-
512
- workspace_root
513
- .join("test_documents")
514
- .join(relative_path)
515
- .to_string_lossy()
516
- .to_string()
517
- }
518
-
519
- #[tokio::test]
520
- async fn test_tool_router_has_routes() {
521
- let router = KreuzbergMcp::tool_router();
522
- assert!(router.has_route("extract_file"));
523
- assert!(router.has_route("extract_bytes"));
524
- assert!(router.has_route("batch_extract_files"));
525
- assert!(router.has_route("detect_mime_type"));
526
- assert!(router.has_route("cache_stats"));
527
- assert!(router.has_route("cache_clear"));
528
-
529
- let tools = router.list_all();
530
- assert_eq!(tools.len(), 6);
531
- }
532
-
533
- #[test]
534
- fn test_server_info() {
535
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
536
- let info = server.get_info();
537
-
538
- assert_eq!(info.server_info.name, "kreuzberg-mcp");
539
- assert_eq!(info.server_info.version, env!("CARGO_PKG_VERSION"));
540
- assert!(info.capabilities.tools.is_some());
541
- }
542
-
543
- #[test]
544
- fn test_build_config() {
545
- let default_config = ExtractionConfig::default();
546
-
547
- let config = build_config(&default_config, false, false);
548
- assert!(config.ocr.is_none());
549
- assert!(!config.force_ocr);
550
-
551
- let config = build_config(&default_config, true, false);
552
- assert!(config.ocr.is_some());
553
- assert!(!config.force_ocr);
554
-
555
- let config = build_config(&default_config, true, true);
556
- assert!(config.ocr.is_some());
557
- assert!(config.force_ocr);
558
- }
559
-
560
- #[test]
561
- fn test_with_config_stores_provided_config() {
562
- let custom_config = ExtractionConfig {
563
- force_ocr: true,
564
- use_cache: false,
565
- ..Default::default()
566
- };
567
-
568
- let server = KreuzbergMcp::with_config(custom_config);
569
-
570
- assert!(server.default_config.force_ocr);
571
- assert!(!server.default_config.use_cache);
572
- }
573
-
574
- #[test]
575
- fn test_map_validation_error_to_invalid_params() {
576
- let error = KreuzbergError::validation("invalid file path");
577
- let mcp_error = map_kreuzberg_error_to_mcp(error);
578
-
579
- assert_eq!(mcp_error.code.0, -32602);
580
- assert!(mcp_error.message.contains("Validation error"));
581
- assert!(mcp_error.message.contains("invalid file path"));
582
- }
583
-
584
- #[test]
585
- fn test_map_validation_error_with_source_preserves_chain() {
586
- let source = std::io::Error::new(std::io::ErrorKind::InvalidInput, "bad param");
587
- let error = KreuzbergError::validation_with_source("invalid configuration", source);
588
- let mcp_error = map_kreuzberg_error_to_mcp(error);
589
-
590
- assert_eq!(mcp_error.code.0, -32602);
591
- assert!(mcp_error.message.contains("Validation error"));
592
- assert!(mcp_error.message.contains("invalid configuration"));
593
- assert!(mcp_error.message.contains("caused by"));
594
- }
595
-
596
- #[test]
597
- fn test_map_unsupported_format_to_invalid_params() {
598
- let error = KreuzbergError::UnsupportedFormat("application/unknown".to_string());
599
- let mcp_error = map_kreuzberg_error_to_mcp(error);
600
-
601
- assert_eq!(mcp_error.code.0, -32602);
602
- assert!(mcp_error.message.contains("Unsupported format"));
603
- assert!(mcp_error.message.contains("application/unknown"));
604
- }
605
-
606
- #[test]
607
- fn test_map_missing_dependency_to_invalid_params() {
608
- let error = KreuzbergError::MissingDependency("tesseract".to_string());
609
- let mcp_error = map_kreuzberg_error_to_mcp(error);
610
-
611
- assert_eq!(mcp_error.code.0, -32602);
612
- assert!(mcp_error.message.contains("Missing required dependency"));
613
- assert!(mcp_error.message.contains("tesseract"));
614
- assert!(mcp_error.message.contains("Please install"));
615
- }
616
-
617
- #[test]
618
- fn test_map_parsing_error_to_parse_error() {
619
- let error = KreuzbergError::parsing("corrupt PDF file");
620
- let mcp_error = map_kreuzberg_error_to_mcp(error);
621
-
622
- assert_eq!(mcp_error.code.0, -32700);
623
- assert!(mcp_error.message.contains("Parsing error"));
624
- assert!(mcp_error.message.contains("corrupt PDF file"));
625
- }
626
-
627
- #[test]
628
- fn test_map_parsing_error_with_source_preserves_chain() {
629
- let source = std::io::Error::new(std::io::ErrorKind::InvalidData, "malformed data");
630
- let error = KreuzbergError::parsing_with_source("failed to parse document", source);
631
- let mcp_error = map_kreuzberg_error_to_mcp(error);
632
-
633
- assert_eq!(mcp_error.code.0, -32700);
634
- assert!(mcp_error.message.contains("Parsing error"));
635
- assert!(mcp_error.message.contains("failed to parse document"));
636
- assert!(mcp_error.message.contains("caused by"));
637
- }
638
-
639
- #[test]
640
- fn test_map_io_error_to_internal_error() {
641
- let io_error = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
642
- let error = KreuzbergError::Io(io_error);
643
- let mcp_error = map_kreuzberg_error_to_mcp(error);
644
-
645
- assert_eq!(mcp_error.code.0, -32603);
646
- assert!(mcp_error.message.contains("System I/O error"));
647
- assert!(mcp_error.message.contains("file not found"));
648
- }
649
-
650
- #[test]
651
- fn test_map_ocr_error_to_internal_error() {
652
- let error = KreuzbergError::ocr("tesseract failed");
653
- let mcp_error = map_kreuzberg_error_to_mcp(error);
654
-
655
- assert_eq!(mcp_error.code.0, -32603);
656
- assert!(mcp_error.message.contains("OCR processing error"));
657
- assert!(mcp_error.message.contains("tesseract failed"));
658
- }
659
-
660
- #[test]
661
- fn test_map_cache_error_to_internal_error() {
662
- let error = KreuzbergError::cache("cache write failed");
663
- let mcp_error = map_kreuzberg_error_to_mcp(error);
664
-
665
- assert_eq!(mcp_error.code.0, -32603);
666
- assert!(mcp_error.message.contains("Cache error"));
667
- assert!(mcp_error.message.contains("cache write failed"));
668
- }
669
-
670
- #[test]
671
- fn test_map_image_processing_error_to_internal_error() {
672
- let error = KreuzbergError::image_processing("resize failed");
673
- let mcp_error = map_kreuzberg_error_to_mcp(error);
674
-
675
- assert_eq!(mcp_error.code.0, -32603);
676
- assert!(mcp_error.message.contains("Image processing error"));
677
- assert!(mcp_error.message.contains("resize failed"));
678
- }
679
-
680
- #[test]
681
- fn test_map_serialization_error_to_internal_error() {
682
- let error = KreuzbergError::serialization("JSON encode failed");
683
- let mcp_error = map_kreuzberg_error_to_mcp(error);
684
-
685
- assert_eq!(mcp_error.code.0, -32603);
686
- assert!(mcp_error.message.contains("Serialization error"));
687
- assert!(mcp_error.message.contains("JSON encode failed"));
688
- }
689
-
690
- #[test]
691
- fn test_map_plugin_error_to_internal_error() {
692
- let error = KreuzbergError::Plugin {
693
- message: "extraction failed".to_string(),
694
- plugin_name: "pdf-extractor".to_string(),
695
- };
696
- let mcp_error = map_kreuzberg_error_to_mcp(error);
697
-
698
- assert_eq!(mcp_error.code.0, -32603);
699
- assert!(mcp_error.message.contains("Plugin 'pdf-extractor' error"));
700
- assert!(mcp_error.message.contains("extraction failed"));
701
- }
702
-
703
- #[test]
704
- fn test_map_lock_poisoned_error_to_internal_error() {
705
- let error = KreuzbergError::LockPoisoned("registry lock poisoned".to_string());
706
- let mcp_error = map_kreuzberg_error_to_mcp(error);
707
-
708
- assert_eq!(mcp_error.code.0, -32603);
709
- assert!(mcp_error.message.contains("Internal lock poisoned"));
710
- assert!(mcp_error.message.contains("registry lock poisoned"));
711
- }
712
-
713
- #[test]
714
- fn test_map_other_error_to_internal_error() {
715
- let error = KreuzbergError::Other("unexpected error".to_string());
716
- let mcp_error = map_kreuzberg_error_to_mcp(error);
717
-
718
- assert_eq!(mcp_error.code.0, -32603);
719
- assert!(mcp_error.message.contains("unexpected error"));
720
- }
721
-
722
- #[test]
723
- fn test_error_type_differentiation() {
724
- let validation = KreuzbergError::validation("test");
725
- let parsing = KreuzbergError::parsing("test");
726
- let io = KreuzbergError::Io(std::io::Error::other("test"));
727
-
728
- let val_mcp = map_kreuzberg_error_to_mcp(validation);
729
- let parse_mcp = map_kreuzberg_error_to_mcp(parsing);
730
- let io_mcp = map_kreuzberg_error_to_mcp(io);
731
-
732
- assert_eq!(val_mcp.code.0, -32602);
733
- assert_eq!(parse_mcp.code.0, -32700);
734
- assert_eq!(io_mcp.code.0, -32603);
735
-
736
- assert_ne!(val_mcp.code.0, parse_mcp.code.0);
737
- assert_ne!(val_mcp.code.0, io_mcp.code.0);
738
- assert_ne!(parse_mcp.code.0, io_mcp.code.0);
739
- }
740
-
741
- #[test]
742
- fn test_format_extraction_result_with_content() {
743
- let result = KreuzbergResult {
744
- content: "Sample extracted text".to_string(),
745
- mime_type: "text/plain".to_string(),
746
- metadata: crate::Metadata::default(),
747
- tables: vec![],
748
- detected_languages: None,
749
- chunks: None,
750
- images: None,
751
- };
752
-
753
- let formatted = format_extraction_result(&result);
754
-
755
- assert!(formatted.contains("Content (21 characters)"));
756
- assert!(formatted.contains("Sample extracted text"));
757
- assert!(formatted.contains("Metadata:"));
758
- }
759
-
760
- #[test]
761
- fn test_format_extraction_result_with_tables() {
762
- let result = KreuzbergResult {
763
- content: "Document with tables".to_string(),
764
- mime_type: "application/pdf".to_string(),
765
- metadata: crate::Metadata::default(),
766
- tables: vec![
767
- crate::Table {
768
- cells: vec![
769
- vec!["Col1".to_string(), "Col2".to_string()],
770
- vec!["A".to_string(), "B".to_string()],
771
- ],
772
- page_number: 1,
773
- markdown: "| Col1 | Col2 |\n|------|------|\n| A | B |".to_string(),
774
- },
775
- crate::Table {
776
- cells: vec![
777
- vec!["X".to_string(), "Y".to_string()],
778
- vec!["1".to_string(), "2".to_string()],
779
- ],
780
- page_number: 2,
781
- markdown: "| X | Y |\n|---|---|\n| 1 | 2 |".to_string(),
782
- },
783
- ],
784
- detected_languages: None,
785
- chunks: None,
786
- images: None,
787
- };
788
-
789
- let formatted = format_extraction_result(&result);
790
-
791
- assert!(formatted.contains("Tables (2)"));
792
- assert!(formatted.contains("Table 1 (page 1)"));
793
- assert!(formatted.contains("Table 2 (page 2)"));
794
- assert!(formatted.contains("| Col1 | Col2 |"));
795
- assert!(formatted.contains("| X | Y |"));
796
- }
797
-
798
- #[test]
799
- fn test_format_extraction_result_empty_content() {
800
- let result = KreuzbergResult {
801
- content: String::new(),
802
- mime_type: "text/plain".to_string(),
803
- metadata: crate::Metadata::default(),
804
- tables: vec![],
805
- detected_languages: None,
806
- chunks: None,
807
- images: None,
808
- };
809
-
810
- let formatted = format_extraction_result(&result);
811
-
812
- assert!(formatted.contains("Content (0 characters)"));
813
- assert!(formatted.contains("Metadata:"));
814
- }
815
-
816
- #[test]
817
- fn test_format_extraction_result_no_tables() {
818
- let result = KreuzbergResult {
819
- content: "Simple text".to_string(),
820
- mime_type: "text/plain".to_string(),
821
- metadata: crate::Metadata::default(),
822
- tables: vec![],
823
- detected_languages: None,
824
- chunks: None,
825
- images: None,
826
- };
827
-
828
- let formatted = format_extraction_result(&result);
829
-
830
- assert!(formatted.contains("Simple text"));
831
- assert!(!formatted.contains("Tables"));
832
- }
833
-
834
- #[tokio::test]
835
- async fn test_extract_file_sync_with_valid_pdf() {
836
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
837
- let params = ExtractFileParams {
838
- path: get_test_path("pdfs_with_tables/tiny.pdf").to_string(),
839
- mime_type: None,
840
- enable_ocr: false,
841
- force_ocr: false,
842
- r#async: true,
843
- };
844
-
845
- let result = server.extract_file(Parameters(params)).await;
846
-
847
- assert!(result.is_ok());
848
- let call_result = result.unwrap();
849
- if let Some(content) = call_result.content.first() {
850
- match &content.raw {
851
- RawContent::Text(text) => {
852
- assert!(!text.text.is_empty());
853
- assert!(text.text.contains("Content"));
854
- }
855
- _ => panic!("Expected text content"),
856
- }
857
- } else {
858
- panic!("Expected content in result");
859
- }
860
- }
861
-
862
- #[tokio::test]
863
- async fn test_extract_file_async_with_valid_pdf() {
864
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
865
- let params = ExtractFileParams {
866
- path: get_test_path("pdfs_with_tables/tiny.pdf").to_string(),
867
- mime_type: None,
868
- enable_ocr: false,
869
- force_ocr: false,
870
- r#async: true,
871
- };
872
-
873
- let result = server.extract_file(Parameters(params)).await;
874
-
875
- assert!(result.is_ok());
876
- let call_result = result.unwrap();
877
- if let Some(content) = call_result.content.first() {
878
- match &content.raw {
879
- RawContent::Text(text) => {
880
- assert!(!text.text.is_empty());
881
- }
882
- _ => panic!("Expected text content"),
883
- }
884
- } else {
885
- panic!("Expected content in result");
886
- }
887
- }
888
-
889
- #[tokio::test]
890
- async fn test_extract_file_with_invalid_path() {
891
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
892
- let params = ExtractFileParams {
893
- path: "/nonexistent/file.pdf".to_string(),
894
- mime_type: None,
895
- enable_ocr: false,
896
- force_ocr: false,
897
- r#async: true,
898
- };
899
-
900
- let result = server.extract_file(Parameters(params)).await;
901
-
902
- assert!(result.is_err());
903
- let error = result.unwrap_err();
904
- assert!(error.code.0 == -32602 || error.code.0 == -32603);
905
- }
906
-
907
- #[tokio::test]
908
- async fn test_extract_file_with_mime_type_hint() {
909
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
910
- let params = ExtractFileParams {
911
- path: get_test_path("pdfs_with_tables/tiny.pdf").to_string(),
912
- mime_type: Some("application/pdf".to_string()),
913
- enable_ocr: false,
914
- force_ocr: false,
915
- r#async: true,
916
- };
917
-
918
- let result = server.extract_file(Parameters(params)).await;
919
-
920
- assert!(result.is_ok());
921
- }
922
-
923
- #[tokio::test]
924
- async fn test_extract_file_with_ocr_enabled() {
925
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
926
- let params = ExtractFileParams {
927
- path: get_test_path("pdfs_with_tables/tiny.pdf").to_string(),
928
- mime_type: None,
929
- enable_ocr: true,
930
- force_ocr: false,
931
- r#async: true,
932
- };
933
-
934
- let result = server.extract_file(Parameters(params)).await;
935
-
936
- assert!(result.is_ok() || result.is_err());
937
- }
938
-
939
- #[tokio::test]
940
- async fn test_extract_file_with_force_ocr() {
941
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
942
- let params = ExtractFileParams {
943
- path: get_test_path("pdfs_with_tables/tiny.pdf").to_string(),
944
- mime_type: None,
945
- enable_ocr: true,
946
- force_ocr: true,
947
- r#async: true,
948
- };
949
-
950
- let result = server.extract_file(Parameters(params)).await;
951
-
952
- assert!(result.is_ok() || result.is_err());
953
- }
954
-
955
- #[tokio::test]
956
- async fn test_extract_bytes_sync_with_valid_data() {
957
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
958
-
959
- let text_content = b"Hello, world!";
960
- let encoded = BASE64_STANDARD.encode(text_content);
961
-
962
- let params = ExtractBytesParams {
963
- data: encoded,
964
- mime_type: Some("text/plain".to_string()),
965
- enable_ocr: false,
966
- force_ocr: false,
967
- r#async: true,
968
- };
969
-
970
- let result = server.extract_bytes(Parameters(params)).await;
971
-
972
- assert!(result.is_ok());
973
- let call_result = result.unwrap();
974
- if let Some(content) = call_result.content.first() {
975
- match &content.raw {
976
- RawContent::Text(text) => {
977
- assert!(text.text.contains("Hello, world!"));
978
- }
979
- _ => panic!("Expected text content"),
980
- }
981
- } else {
982
- panic!("Expected content in result");
983
- }
984
- }
985
-
986
- #[tokio::test]
987
- async fn test_extract_bytes_async_with_valid_data() {
988
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
989
-
990
- let text_content = b"Async extraction test";
991
- let encoded = BASE64_STANDARD.encode(text_content);
992
-
993
- let params = ExtractBytesParams {
994
- data: encoded,
995
- mime_type: Some("text/plain".to_string()),
996
- enable_ocr: false,
997
- force_ocr: false,
998
- r#async: true,
999
- };
1000
-
1001
- let result = server.extract_bytes(Parameters(params)).await;
1002
-
1003
- assert!(result.is_ok());
1004
- }
1005
-
1006
- #[tokio::test]
1007
- async fn test_extract_bytes_with_invalid_base64() {
1008
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1009
-
1010
- let params = ExtractBytesParams {
1011
- data: "not-valid-base64!!!".to_string(),
1012
- mime_type: None,
1013
- enable_ocr: false,
1014
- force_ocr: false,
1015
- r#async: true,
1016
- };
1017
-
1018
- let result = server.extract_bytes(Parameters(params)).await;
1019
-
1020
- assert!(result.is_err());
1021
- let error = result.unwrap_err();
1022
- assert_eq!(error.code.0, -32602);
1023
- assert!(error.message.contains("Invalid base64"));
1024
- }
1025
-
1026
- #[tokio::test]
1027
- async fn test_extract_bytes_without_mime_type() {
1028
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1029
-
1030
- let text_content = b"Test content";
1031
- let encoded = BASE64_STANDARD.encode(text_content);
1032
-
1033
- let params = ExtractBytesParams {
1034
- data: encoded,
1035
- mime_type: None,
1036
- enable_ocr: false,
1037
- force_ocr: false,
1038
- r#async: true,
1039
- };
1040
-
1041
- let result = server.extract_bytes(Parameters(params)).await;
1042
-
1043
- assert!(result.is_ok() || result.is_err());
1044
- }
1045
-
1046
- #[tokio::test]
1047
- async fn test_extract_bytes_with_ocr_enabled() {
1048
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1049
-
1050
- let text_content = b"OCR test content";
1051
- let encoded = BASE64_STANDARD.encode(text_content);
1052
-
1053
- let params = ExtractBytesParams {
1054
- data: encoded,
1055
- mime_type: Some("text/plain".to_string()),
1056
- enable_ocr: true,
1057
- force_ocr: false,
1058
- r#async: true,
1059
- };
1060
-
1061
- let result = server.extract_bytes(Parameters(params)).await;
1062
-
1063
- assert!(result.is_ok() || result.is_err());
1064
- }
1065
-
1066
- #[tokio::test]
1067
- async fn test_batch_extract_files_sync_with_valid_files() {
1068
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1069
- let params = BatchExtractFilesParams {
1070
- paths: vec![get_test_path("pdfs_with_tables/tiny.pdf").to_string()],
1071
- enable_ocr: false,
1072
- force_ocr: false,
1073
- r#async: true,
1074
- };
1075
-
1076
- let result = server.batch_extract_files(Parameters(params)).await;
1077
-
1078
- assert!(result.is_ok());
1079
- let call_result = result.unwrap();
1080
- if let Some(content) = call_result.content.first() {
1081
- match &content.raw {
1082
- RawContent::Text(text) => {
1083
- assert!(text.text.contains("Document 1"));
1084
- assert!(text.text.contains("tiny.pdf"));
1085
- }
1086
- _ => panic!("Expected text content"),
1087
- }
1088
- } else {
1089
- panic!("Expected content in result");
1090
- }
1091
- }
1092
-
1093
- #[tokio::test]
1094
- async fn test_batch_extract_files_async_with_multiple_files() {
1095
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1096
- let params = BatchExtractFilesParams {
1097
- paths: vec![
1098
- get_test_path("pdfs_with_tables/tiny.pdf").to_string(),
1099
- get_test_path("pdfs_with_tables/medium.pdf").to_string(),
1100
- ],
1101
- enable_ocr: false,
1102
- force_ocr: false,
1103
- r#async: true,
1104
- };
1105
-
1106
- let result = server.batch_extract_files(Parameters(params)).await;
1107
-
1108
- assert!(result.is_ok());
1109
- let call_result = result.unwrap();
1110
- if let Some(content) = call_result.content.first() {
1111
- match &content.raw {
1112
- RawContent::Text(text) => {
1113
- assert!(text.text.contains("Document 1"));
1114
- assert!(text.text.contains("Document 2"));
1115
- }
1116
- _ => panic!("Expected text content"),
1117
- }
1118
- } else {
1119
- panic!("Expected content in result");
1120
- }
1121
- }
1122
-
1123
- #[tokio::test]
1124
- async fn test_batch_extract_files_with_empty_list() {
1125
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1126
- let params = BatchExtractFilesParams {
1127
- paths: vec![],
1128
- enable_ocr: false,
1129
- force_ocr: false,
1130
- r#async: true,
1131
- };
1132
-
1133
- let result = server.batch_extract_files(Parameters(params)).await;
1134
-
1135
- assert!(result.is_ok());
1136
- let call_result = result.unwrap();
1137
- if let Some(content) = call_result.content.first() {
1138
- match &content.raw {
1139
- RawContent::Text(text) => {
1140
- assert!(text.text.is_empty() || text.text.trim().is_empty());
1141
- }
1142
- _ => panic!("Expected text content"),
1143
- }
1144
- } else {
1145
- panic!("Expected content in result");
1146
- }
1147
- }
1148
-
1149
- #[tokio::test]
1150
- async fn test_batch_extract_files_with_invalid_file() {
1151
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1152
- let params = BatchExtractFilesParams {
1153
- paths: vec!["/nonexistent/file.pdf".to_string()],
1154
- enable_ocr: false,
1155
- force_ocr: false,
1156
- r#async: true,
1157
- };
1158
-
1159
- let result = server.batch_extract_files(Parameters(params)).await;
1160
-
1161
- assert!(result.is_ok() || result.is_err());
1162
- }
1163
-
1164
- #[tokio::test]
1165
- async fn test_detect_mime_type_with_valid_file() {
1166
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1167
- let params = DetectMimeTypeParams {
1168
- path: get_test_path("pdfs_with_tables/tiny.pdf").to_string(),
1169
- use_content: true,
1170
- };
1171
-
1172
- let result = server.detect_mime_type(Parameters(params));
1173
-
1174
- assert!(result.is_ok());
1175
- let call_result = result.unwrap();
1176
- if let Some(content) = call_result.content.first() {
1177
- match &content.raw {
1178
- RawContent::Text(text) => {
1179
- assert!(text.text.contains("application/pdf") || text.text.contains("pdf"));
1180
- }
1181
- _ => panic!("Expected text content"),
1182
- }
1183
- } else {
1184
- panic!("Expected content in result");
1185
- }
1186
- }
1187
-
1188
- #[tokio::test]
1189
- async fn test_detect_mime_type_without_content_detection() {
1190
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1191
- let params = DetectMimeTypeParams {
1192
- path: get_test_path("pdfs_with_tables/tiny.pdf").to_string(),
1193
- use_content: false,
1194
- };
1195
-
1196
- let result = server.detect_mime_type(Parameters(params));
1197
-
1198
- assert!(result.is_ok());
1199
- }
1200
-
1201
- #[tokio::test]
1202
- async fn test_detect_mime_type_with_invalid_file() {
1203
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1204
- let params = DetectMimeTypeParams {
1205
- path: "/nonexistent/file.pdf".to_string(),
1206
- use_content: true,
1207
- };
1208
-
1209
- let result = server.detect_mime_type(Parameters(params));
1210
-
1211
- assert!(result.is_err());
1212
- let error = result.unwrap_err();
1213
- assert!(error.code.0 == -32602 || error.code.0 == -32603);
1214
- }
1215
-
1216
- #[tokio::test]
1217
- async fn test_cache_stats_returns_statistics() {
1218
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1219
-
1220
- let result = server.cache_stats(Parameters(()));
1221
-
1222
- assert!(result.is_ok());
1223
- let call_result = result.unwrap();
1224
- if let Some(content) = call_result.content.first() {
1225
- match &content.raw {
1226
- RawContent::Text(text) => {
1227
- assert!(text.text.contains("Cache Statistics"));
1228
- assert!(text.text.contains("Directory:"));
1229
- assert!(text.text.contains("Total files:"));
1230
- assert!(text.text.contains("Total size:"));
1231
- assert!(text.text.contains("Available space:"));
1232
- }
1233
- _ => panic!("Expected text content"),
1234
- }
1235
- } else {
1236
- panic!("Expected content in result");
1237
- }
1238
- }
1239
-
1240
- #[tokio::test]
1241
- async fn test_cache_clear_returns_result() {
1242
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1243
-
1244
- let result = server.cache_clear(Parameters(()));
1245
-
1246
- assert!(result.is_ok());
1247
- let call_result = result.unwrap();
1248
- if let Some(content) = call_result.content.first() {
1249
- match &content.raw {
1250
- RawContent::Text(text) => {
1251
- assert!(text.text.contains("Cache cleared"));
1252
- assert!(text.text.contains("Directory:"));
1253
- assert!(text.text.contains("Removed files:"));
1254
- assert!(text.text.contains("Freed space:"));
1255
- }
1256
- _ => panic!("Expected text content"),
1257
- }
1258
- } else {
1259
- panic!("Expected content in result");
1260
- }
1261
- }
1262
-
1263
- #[test]
1264
- fn test_new_creates_server_with_default_config() {
1265
- let server = KreuzbergMcp::new();
1266
- assert!(server.is_ok());
1267
- }
1268
-
1269
- #[test]
1270
- fn test_default_creates_server_without_panic() {
1271
- let server = KreuzbergMcp::default();
1272
- let info = server.get_info();
1273
- assert_eq!(info.server_info.name, "kreuzberg-mcp");
1274
- }
1275
-
1276
- #[test]
1277
- fn test_server_info_has_correct_fields() {
1278
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1279
- let info = server.get_info();
1280
-
1281
- assert_eq!(info.server_info.name, "kreuzberg-mcp");
1282
- assert_eq!(
1283
- info.server_info.title,
1284
- Some("Kreuzberg Document Intelligence MCP Server".to_string())
1285
- );
1286
- assert_eq!(info.server_info.version, env!("CARGO_PKG_VERSION"));
1287
- assert_eq!(
1288
- info.server_info.website_url,
1289
- Some("https://goldziher.github.io/kreuzberg/".to_string())
1290
- );
1291
- assert!(info.instructions.is_some());
1292
- assert!(info.capabilities.tools.is_some());
1293
- }
1294
-
1295
- #[test]
1296
- fn test_build_config_preserves_default_config_settings() {
1297
- let default_config = ExtractionConfig {
1298
- use_cache: false,
1299
- ..Default::default()
1300
- };
1301
-
1302
- let config = build_config(&default_config, false, false);
1303
-
1304
- assert!(!config.use_cache);
1305
- }
1306
-
1307
- #[test]
1308
- fn test_build_config_ocr_disabled_by_default() {
1309
- let default_config = ExtractionConfig::default();
1310
-
1311
- let config = build_config(&default_config, false, false);
1312
-
1313
- assert!(config.ocr.is_none());
1314
- assert!(!config.force_ocr);
1315
- }
1316
-
1317
- #[test]
1318
- fn test_build_config_ocr_enabled_creates_tesseract_config() {
1319
- let default_config = ExtractionConfig::default();
1320
-
1321
- let config = build_config(&default_config, true, false);
1322
-
1323
- assert!(config.ocr.is_some());
1324
- let ocr_config = config.ocr.unwrap();
1325
- assert_eq!(ocr_config.backend, "tesseract");
1326
- assert_eq!(ocr_config.language, "eng");
1327
- }
1328
-
1329
- #[test]
1330
- fn test_extract_file_params_defaults() {
1331
- let json = r#"{"path": "/test.pdf"}"#;
1332
- let params: ExtractFileParams = serde_json::from_str(json).unwrap();
1333
-
1334
- assert_eq!(params.path, "/test.pdf");
1335
- assert_eq!(params.mime_type, None);
1336
- assert!(!params.enable_ocr);
1337
- assert!(!params.force_ocr);
1338
- assert!(!params.r#async);
1339
- }
1340
-
1341
- #[test]
1342
- fn test_extract_bytes_params_defaults() {
1343
- let json = r#"{"data": "SGVsbG8="}"#;
1344
- let params: ExtractBytesParams = serde_json::from_str(json).unwrap();
1345
-
1346
- assert_eq!(params.data, "SGVsbG8=");
1347
- assert_eq!(params.mime_type, None);
1348
- assert!(!params.enable_ocr);
1349
- assert!(!params.force_ocr);
1350
- assert!(!params.r#async);
1351
- }
1352
-
1353
- #[test]
1354
- fn test_batch_extract_files_params_defaults() {
1355
- let json = r#"{"paths": ["/a.pdf", "/b.pdf"]}"#;
1356
- let params: BatchExtractFilesParams = serde_json::from_str(json).unwrap();
1357
-
1358
- assert_eq!(params.paths.len(), 2);
1359
- assert!(!params.enable_ocr);
1360
- assert!(!params.force_ocr);
1361
- assert!(!params.r#async);
1362
- }
1363
-
1364
- #[test]
1365
- fn test_detect_mime_type_params_defaults() {
1366
- let json = r#"{"path": "/test.pdf"}"#;
1367
- let params: DetectMimeTypeParams = serde_json::from_str(json).unwrap();
1368
-
1369
- assert_eq!(params.path, "/test.pdf");
1370
- assert!(params.use_content);
1371
- }
1372
-
1373
- #[test]
1374
- fn test_detect_mime_type_params_use_content_false() {
1375
- let json = r#"{"path": "/test.pdf", "use_content": false}"#;
1376
- let params: DetectMimeTypeParams = serde_json::from_str(json).unwrap();
1377
-
1378
- assert!(!params.use_content);
1379
- }
1380
-
1381
- #[test]
1382
- fn test_mcp_server_info_protocol_version() {
1383
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1384
- let info = server.get_info();
1385
-
1386
- assert_eq!(info.protocol_version, ProtocolVersion::default());
1387
- }
1388
-
1389
- #[test]
1390
- fn test_mcp_server_info_has_all_required_fields() {
1391
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1392
- let info = server.get_info();
1393
-
1394
- assert!(!info.server_info.name.is_empty());
1395
- assert!(!info.server_info.version.is_empty());
1396
-
1397
- assert!(info.server_info.title.is_some());
1398
- assert!(info.server_info.website_url.is_some());
1399
- assert!(info.instructions.is_some());
1400
- }
1401
-
1402
- #[test]
1403
- fn test_mcp_server_capabilities_declares_tools() {
1404
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1405
- let info = server.get_info();
1406
-
1407
- assert!(info.capabilities.tools.is_some());
1408
- }
1409
-
1410
- #[test]
1411
- fn test_mcp_server_name_follows_convention() {
1412
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1413
- let info = server.get_info();
1414
-
1415
- assert_eq!(info.server_info.name, "kreuzberg-mcp");
1416
- assert!(!info.server_info.name.contains('_'));
1417
- assert!(!info.server_info.name.contains(' '));
1418
- }
1419
-
1420
- #[test]
1421
- fn test_mcp_version_matches_cargo_version() {
1422
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1423
- let info = server.get_info();
1424
-
1425
- assert_eq!(info.server_info.version, env!("CARGO_PKG_VERSION"));
1426
- }
1427
-
1428
- #[test]
1429
- fn test_mcp_instructions_are_helpful() {
1430
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1431
- let info = server.get_info();
1432
-
1433
- let instructions = info.instructions.expect("Instructions should be present");
1434
-
1435
- assert!(instructions.contains("extract") || instructions.contains("Extract"));
1436
- assert!(instructions.contains("OCR") || instructions.contains("ocr"));
1437
- assert!(instructions.contains("document"));
1438
- }
1439
-
1440
- #[tokio::test]
1441
- async fn test_all_tools_are_registered() {
1442
- let router = KreuzbergMcp::tool_router();
1443
-
1444
- let expected_tools = vec![
1445
- "extract_file",
1446
- "extract_bytes",
1447
- "batch_extract_files",
1448
- "detect_mime_type",
1449
- "cache_stats",
1450
- "cache_clear",
1451
- ];
1452
-
1453
- for tool_name in expected_tools {
1454
- assert!(router.has_route(tool_name), "Tool '{}' should be registered", tool_name);
1455
- }
1456
- }
1457
-
1458
- #[tokio::test]
1459
- async fn test_tool_count_is_correct() {
1460
- let router = KreuzbergMcp::tool_router();
1461
- let tools = router.list_all();
1462
-
1463
- assert_eq!(tools.len(), 6, "Expected 6 tools, found {}", tools.len());
1464
- }
1465
-
1466
- #[tokio::test]
1467
- async fn test_tools_have_descriptions() {
1468
- let router = KreuzbergMcp::tool_router();
1469
- let tools = router.list_all();
1470
-
1471
- for tool in tools {
1472
- assert!(
1473
- tool.description.is_some(),
1474
- "Tool '{}' should have a description",
1475
- tool.name
1476
- );
1477
- let desc = tool.description.as_ref().unwrap();
1478
- assert!(!desc.is_empty(), "Tool '{}' description should not be empty", tool.name);
1479
- }
1480
- }
1481
-
1482
- #[tokio::test]
1483
- async fn test_extract_file_tool_has_correct_schema() {
1484
- let router = KreuzbergMcp::tool_router();
1485
- let tools = router.list_all();
1486
-
1487
- let extract_file_tool = tools
1488
- .iter()
1489
- .find(|t| t.name == "extract_file")
1490
- .expect("extract_file tool should exist");
1491
-
1492
- assert!(extract_file_tool.description.is_some());
1493
-
1494
- assert!(!extract_file_tool.input_schema.is_empty());
1495
- }
1496
-
1497
- #[tokio::test]
1498
- async fn test_all_tools_have_input_schemas() {
1499
- let router = KreuzbergMcp::tool_router();
1500
- let tools = router.list_all();
1501
-
1502
- for tool in tools {
1503
- assert!(
1504
- !tool.input_schema.is_empty(),
1505
- "Tool '{}' should have an input schema with fields",
1506
- tool.name
1507
- );
1508
- }
1509
- }
1510
-
1511
- #[test]
1512
- fn test_server_creation_with_custom_config() {
1513
- let custom_config = ExtractionConfig {
1514
- force_ocr: true,
1515
- use_cache: false,
1516
- ocr: Some(crate::OcrConfig {
1517
- backend: "tesseract".to_string(),
1518
- language: "spa".to_string(),
1519
- tesseract_config: None,
1520
- }),
1521
- ..Default::default()
1522
- };
1523
-
1524
- let server = KreuzbergMcp::with_config(custom_config.clone());
1525
-
1526
- assert_eq!(server.default_config.force_ocr, custom_config.force_ocr);
1527
- assert_eq!(server.default_config.use_cache, custom_config.use_cache);
1528
- }
1529
-
1530
- #[test]
1531
- fn test_server_clone_preserves_config() {
1532
- let custom_config = ExtractionConfig {
1533
- force_ocr: true,
1534
- ..Default::default()
1535
- };
1536
-
1537
- let server1 = KreuzbergMcp::with_config(custom_config);
1538
- let server2 = server1.clone();
1539
-
1540
- assert_eq!(server1.default_config.force_ocr, server2.default_config.force_ocr);
1541
- }
1542
-
1543
- #[tokio::test]
1544
- async fn test_extract_bytes_with_empty_data() {
1545
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1546
-
1547
- let params = ExtractBytesParams {
1548
- data: String::new(),
1549
- mime_type: Some("text/plain".to_string()),
1550
- enable_ocr: false,
1551
- force_ocr: false,
1552
- r#async: true,
1553
- };
1554
-
1555
- let result = server.extract_bytes(Parameters(params)).await;
1556
-
1557
- assert!(result.is_ok() || result.is_err());
1558
- }
1559
-
1560
- #[tokio::test]
1561
- async fn test_extract_bytes_with_valid_pdf_bytes() {
1562
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1563
-
1564
- let pdf_path = get_test_path("pdfs_with_tables/tiny.pdf");
1565
-
1566
- if std::path::Path::new(&pdf_path).exists() {
1567
- let pdf_bytes = std::fs::read(&pdf_path).unwrap();
1568
- let encoded = BASE64_STANDARD.encode(&pdf_bytes);
1569
-
1570
- let params = ExtractBytesParams {
1571
- data: encoded,
1572
- mime_type: Some("application/pdf".to_string()),
1573
- enable_ocr: false,
1574
- force_ocr: false,
1575
- r#async: true,
1576
- };
1577
-
1578
- let result = server.extract_bytes(Parameters(params)).await;
1579
-
1580
- assert!(result.is_ok(), "PDF bytes extraction should succeed");
1581
- let call_result = result.unwrap();
1582
- assert!(!call_result.content.is_empty());
1583
- }
1584
- }
1585
-
1586
- #[tokio::test]
1587
- async fn test_extract_bytes_mime_type_auto_detection() {
1588
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1589
-
1590
- let text_content = b"Plain text content for testing";
1591
- let encoded = BASE64_STANDARD.encode(text_content);
1592
-
1593
- let params = ExtractBytesParams {
1594
- data: encoded,
1595
- mime_type: None,
1596
- enable_ocr: false,
1597
- force_ocr: false,
1598
- r#async: true,
1599
- };
1600
-
1601
- let result = server.extract_bytes(Parameters(params)).await;
1602
-
1603
- assert!(result.is_ok() || result.is_err());
1604
- }
1605
-
1606
- #[tokio::test]
1607
- async fn test_batch_extract_preserves_file_order() {
1608
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1609
-
1610
- let file1 = get_test_path("pdfs_with_tables/tiny.pdf");
1611
- let file2 = get_test_path("pdfs_with_tables/medium.pdf");
1612
-
1613
- if std::path::Path::new(&file1).exists() && std::path::Path::new(&file2).exists() {
1614
- let params = BatchExtractFilesParams {
1615
- paths: vec![file1.to_string(), file2.to_string()],
1616
- enable_ocr: false,
1617
- force_ocr: false,
1618
- r#async: true,
1619
- };
1620
-
1621
- let result = server.batch_extract_files(Parameters(params)).await;
1622
-
1623
- if result.is_ok() {
1624
- let call_result = result.unwrap();
1625
- if let Some(content) = call_result.content.first()
1626
- && let RawContent::Text(text) = &content.raw
1627
- {
1628
- assert!(text.text.contains("Document 1"));
1629
- assert!(text.text.contains("Document 2"));
1630
-
1631
- let doc1_pos = text.text.find("Document 1");
1632
- let doc2_pos = text.text.find("Document 2");
1633
- if let (Some(pos1), Some(pos2)) = (doc1_pos, doc2_pos) {
1634
- assert!(pos1 < pos2, "Documents should be in order");
1635
- }
1636
- }
1637
- }
1638
- }
1639
- }
1640
-
1641
- #[tokio::test]
1642
- async fn test_cache_clear_is_idempotent() {
1643
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1644
-
1645
- let result1 = server.cache_clear(Parameters(()));
1646
- assert!(result1.is_ok());
1647
-
1648
- let result2 = server.cache_clear(Parameters(()));
1649
- assert!(result2.is_ok());
1650
- }
1651
-
1652
- #[tokio::test]
1653
- async fn test_cache_clear_returns_metrics() {
1654
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1655
-
1656
- let result = server.cache_clear(Parameters(()));
1657
-
1658
- assert!(result.is_ok());
1659
- let call_result = result.unwrap();
1660
- if let Some(content) = call_result.content.first()
1661
- && let RawContent::Text(text) = &content.raw
1662
- {
1663
- assert!(text.text.contains("Removed files:"));
1664
- assert!(text.text.contains("Freed space:"));
1665
- }
1666
- }
1667
-
1668
- #[test]
1669
- fn test_error_mapping_preserves_error_context() {
1670
- let validation_error = KreuzbergError::validation("invalid file path");
1671
- let mcp_error = map_kreuzberg_error_to_mcp(validation_error);
1672
-
1673
- assert!(mcp_error.message.contains("invalid file path"));
1674
- }
1675
-
1676
- #[test]
1677
- fn test_io_errors_bubble_up_as_internal() {
1678
- // OSError/RuntimeError must bubble up - system errors need user reports ~keep
1679
- let io_error = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "access denied");
1680
- let kreuzberg_error = KreuzbergError::Io(io_error);
1681
- let mcp_error = map_kreuzberg_error_to_mcp(kreuzberg_error);
1682
-
1683
- assert_eq!(mcp_error.code.0, -32603);
1684
- assert!(mcp_error.message.contains("System I/O error"));
1685
- }
1686
-
1687
- #[test]
1688
- fn test_all_error_variants_have_mappings() {
1689
- let errors = vec![
1690
- KreuzbergError::validation("test"),
1691
- KreuzbergError::UnsupportedFormat("test/unknown".to_string()),
1692
- KreuzbergError::MissingDependency("test-dep".to_string()),
1693
- KreuzbergError::parsing("test"),
1694
- KreuzbergError::Io(std::io::Error::other("test")),
1695
- KreuzbergError::ocr("test"),
1696
- KreuzbergError::cache("test"),
1697
- KreuzbergError::image_processing("test"),
1698
- KreuzbergError::serialization("test"),
1699
- KreuzbergError::Plugin {
1700
- message: "test".to_string(),
1701
- plugin_name: "test-plugin".to_string(),
1702
- },
1703
- KreuzbergError::LockPoisoned("test".to_string()),
1704
- KreuzbergError::Other("test".to_string()),
1705
- ];
1706
-
1707
- for error in errors {
1708
- let mcp_error = map_kreuzberg_error_to_mcp(error);
1709
-
1710
- assert!(mcp_error.code.0 < 0, "Error code should be negative");
1711
-
1712
- assert!(!mcp_error.message.is_empty());
1713
- }
1714
- }
1715
-
1716
- #[tokio::test]
1717
- async fn test_response_includes_metadata() {
1718
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1719
-
1720
- let test_file = get_test_path("pdfs_with_tables/tiny.pdf");
1721
-
1722
- if std::path::Path::new(&test_file).exists() {
1723
- let params = ExtractFileParams {
1724
- path: test_file.to_string(),
1725
- mime_type: None,
1726
- enable_ocr: false,
1727
- force_ocr: false,
1728
- r#async: true,
1729
- };
1730
-
1731
- let result = server.extract_file(Parameters(params)).await;
1732
-
1733
- assert!(result.is_ok());
1734
- let call_result = result.unwrap();
1735
-
1736
- if let Some(content) = call_result.content.first()
1737
- && let RawContent::Text(text) = &content.raw
1738
- {
1739
- assert!(text.text.contains("Metadata:"));
1740
- }
1741
- }
1742
- }
1743
-
1744
- #[tokio::test]
1745
- async fn test_response_includes_content_length() {
1746
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1747
-
1748
- let test_file = get_test_path("pdfs_with_tables/tiny.pdf");
1749
-
1750
- if std::path::Path::new(&test_file).exists() {
1751
- let params = ExtractFileParams {
1752
- path: test_file.to_string(),
1753
- mime_type: None,
1754
- enable_ocr: false,
1755
- force_ocr: false,
1756
- r#async: true,
1757
- };
1758
-
1759
- let result = server.extract_file(Parameters(params)).await;
1760
-
1761
- assert!(result.is_ok());
1762
- let call_result = result.unwrap();
1763
-
1764
- if let Some(content) = call_result.content.first()
1765
- && let RawContent::Text(text) = &content.raw
1766
- {
1767
- assert!(text.text.contains("characters"));
1768
- assert!(text.text.contains("Content"));
1769
- }
1770
- }
1771
- }
1772
-
1773
- #[tokio::test]
1774
- async fn test_server_is_thread_safe() {
1775
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1776
-
1777
- let server1 = server.clone();
1778
- let server2 = server.clone();
1779
-
1780
- let handle1 = tokio::spawn(async move { server1.get_info() });
1781
-
1782
- let handle2 = tokio::spawn(async move { server2.get_info() });
1783
-
1784
- let info1 = handle1.await.unwrap();
1785
- let info2 = handle2.await.unwrap();
1786
-
1787
- assert_eq!(info1.server_info.name, info2.server_info.name);
1788
- }
1789
-
1790
- #[test]
1791
- fn test_extract_file_params_serialization() {
1792
- let params = ExtractFileParams {
1793
- path: "/test.pdf".to_string(),
1794
- mime_type: Some("application/pdf".to_string()),
1795
- enable_ocr: true,
1796
- force_ocr: false,
1797
- r#async: true,
1798
- };
1799
-
1800
- let json = serde_json::to_string(&params).unwrap();
1801
- let deserialized: ExtractFileParams = serde_json::from_str(&json).unwrap();
1802
-
1803
- assert_eq!(params.path, deserialized.path);
1804
- assert_eq!(params.mime_type, deserialized.mime_type);
1805
- assert_eq!(params.enable_ocr, deserialized.enable_ocr);
1806
- assert_eq!(params.force_ocr, deserialized.force_ocr);
1807
- assert_eq!(params.r#async, deserialized.r#async);
1808
- }
1809
-
1810
- #[test]
1811
- fn test_extract_bytes_params_serialization() {
1812
- let params = ExtractBytesParams {
1813
- data: "SGVsbG8=".to_string(),
1814
- mime_type: None,
1815
- enable_ocr: false,
1816
- force_ocr: false,
1817
- r#async: false,
1818
- };
1819
-
1820
- let json = serde_json::to_string(&params).unwrap();
1821
- let deserialized: ExtractBytesParams = serde_json::from_str(&json).unwrap();
1822
-
1823
- assert_eq!(params.data, deserialized.data);
1824
- }
1825
-
1826
- #[test]
1827
- fn test_batch_extract_params_serialization() {
1828
- let params = BatchExtractFilesParams {
1829
- paths: vec!["/a.pdf".to_string(), "/b.pdf".to_string()],
1830
- enable_ocr: true,
1831
- force_ocr: true,
1832
- r#async: true,
1833
- };
1834
-
1835
- let json = serde_json::to_string(&params).unwrap();
1836
- let deserialized: BatchExtractFilesParams = serde_json::from_str(&json).unwrap();
1837
-
1838
- assert_eq!(params.paths, deserialized.paths);
1839
- assert_eq!(params.enable_ocr, deserialized.enable_ocr);
1840
- }
1841
-
1842
- #[test]
1843
- fn test_detect_mime_type_params_serialization() {
1844
- let params = DetectMimeTypeParams {
1845
- path: "/test.pdf".to_string(),
1846
- use_content: false,
1847
- };
1848
-
1849
- let json = serde_json::to_string(&params).unwrap();
1850
- let deserialized: DetectMimeTypeParams = serde_json::from_str(&json).unwrap();
1851
-
1852
- assert_eq!(params.path, deserialized.path);
1853
- assert_eq!(params.use_content, deserialized.use_content);
1854
- }
1855
-
1856
- #[tokio::test]
1857
- async fn test_extract_file_respects_custom_default_config() {
1858
- let custom_config = ExtractionConfig {
1859
- use_cache: false,
1860
- ..Default::default()
1861
- };
1862
-
1863
- let server = KreuzbergMcp::with_config(custom_config);
1864
-
1865
- let test_file = get_test_path("pdfs_with_tables/tiny.pdf");
1866
-
1867
- if std::path::Path::new(&test_file).exists() {
1868
- let params = ExtractFileParams {
1869
- path: test_file.to_string(),
1870
- mime_type: None,
1871
- enable_ocr: false,
1872
- force_ocr: false,
1873
- r#async: true,
1874
- };
1875
-
1876
- let result = server.extract_file(Parameters(params)).await;
1877
-
1878
- assert!(result.is_ok() || result.is_err());
1879
- }
1880
- }
1881
-
1882
- #[tokio::test]
1883
- async fn test_batch_extract_with_single_file() {
1884
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1885
-
1886
- let test_file = get_test_path("pdfs_with_tables/tiny.pdf");
1887
-
1888
- if std::path::Path::new(&test_file).exists() {
1889
- let params = BatchExtractFilesParams {
1890
- paths: vec![test_file.to_string()],
1891
- enable_ocr: false,
1892
- force_ocr: false,
1893
- r#async: true,
1894
- };
1895
-
1896
- let result = server.batch_extract_files(Parameters(params)).await;
1897
-
1898
- assert!(result.is_ok());
1899
- let call_result = result.unwrap();
1900
- assert!(!call_result.content.is_empty());
1901
- }
1902
- }
1903
-
1904
- #[tokio::test]
1905
- async fn test_detect_mime_type_with_extension_only() {
1906
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1907
-
1908
- let test_file = get_test_path("pdfs_with_tables/tiny.pdf");
1909
-
1910
- if std::path::Path::new(&test_file).exists() {
1911
- let params = DetectMimeTypeParams {
1912
- path: test_file.to_string(),
1913
- use_content: false,
1914
- };
1915
-
1916
- let result = server.detect_mime_type(Parameters(params));
1917
-
1918
- assert!(result.is_ok());
1919
- let call_result = result.unwrap();
1920
- if let Some(content) = call_result.content.first()
1921
- && let RawContent::Text(text) = &content.raw
1922
- {
1923
- assert!(text.text.contains("pdf") || text.text.contains("PDF"));
1924
- }
1925
- }
1926
- }
1927
-
1928
- #[tokio::test]
1929
- async fn test_detect_mime_type_with_content_analysis() {
1930
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1931
-
1932
- let test_file = get_test_path("pdfs_with_tables/tiny.pdf");
1933
-
1934
- if std::path::Path::new(&test_file).exists() {
1935
- let params = DetectMimeTypeParams {
1936
- path: test_file.to_string(),
1937
- use_content: true,
1938
- };
1939
-
1940
- let result = server.detect_mime_type(Parameters(params));
1941
-
1942
- assert!(result.is_ok());
1943
- }
1944
- }
1945
-
1946
- #[tokio::test]
1947
- async fn test_cache_stats_returns_valid_data() {
1948
- let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1949
-
1950
- let result = server.cache_stats(Parameters(()));
1951
-
1952
- assert!(result.is_ok());
1953
- let call_result = result.unwrap();
1954
- if let Some(content) = call_result.content.first()
1955
- && let RawContent::Text(text) = &content.raw
1956
- {
1957
- assert!(text.text.contains("Cache Statistics"));
1958
- assert!(text.text.contains("Directory:"));
1959
- assert!(text.text.contains("Total files:"));
1960
- assert!(text.text.contains("Total size:"));
1961
- assert!(text.text.contains("Available space:"));
1962
- assert!(text.text.contains("Oldest file age:"));
1963
- assert!(text.text.contains("Newest file age:"));
1964
- }
1965
- }
1966
- }
1
+ //! MCP server implementation for Kreuzberg.
2
+ //!
3
+ //! This module provides the core MCP server that exposes document extraction
4
+ //! as tools for AI assistants via the Model Context Protocol.
5
+
6
+ use base64::prelude::*;
7
+ use rmcp::{
8
+ ErrorData as McpError, ServerHandler, ServiceExt,
9
+ handler::server::{router::tool::ToolRouter, wrapper::Parameters},
10
+ model::*,
11
+ schemars, tool, tool_handler, tool_router,
12
+ transport::stdio,
13
+ };
14
+
15
+ use crate::{
16
+ ExtractionConfig, ExtractionResult as KreuzbergResult, KreuzbergError, batch_extract_file, batch_extract_file_sync,
17
+ cache, detect_mime_type, extract_bytes, extract_bytes_sync, extract_file, extract_file_sync,
18
+ };
19
+
20
+ /// Request parameters for file extraction.
21
+ #[derive(Debug, serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
22
+ pub struct ExtractFileParams {
23
+ /// Path to the file to extract
24
+ pub path: String,
25
+ /// Optional MIME type hint (auto-detected if not provided)
26
+ #[serde(skip_serializing_if = "Option::is_none")]
27
+ pub mime_type: Option<String>,
28
+ /// Enable OCR for scanned documents
29
+ #[serde(default)]
30
+ pub enable_ocr: bool,
31
+ /// Force OCR even if text extraction succeeds
32
+ #[serde(default)]
33
+ pub force_ocr: bool,
34
+ /// Use async extraction (default: false for sync)
35
+ #[serde(default)]
36
+ pub r#async: bool,
37
+ }
38
+
39
+ /// Request parameters for bytes extraction.
40
+ #[derive(Debug, serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
41
+ pub struct ExtractBytesParams {
42
+ /// Base64-encoded file content
43
+ pub data: String,
44
+ /// Optional MIME type hint (auto-detected if not provided)
45
+ #[serde(skip_serializing_if = "Option::is_none")]
46
+ pub mime_type: Option<String>,
47
+ /// Enable OCR for scanned documents
48
+ #[serde(default)]
49
+ pub enable_ocr: bool,
50
+ /// Force OCR even if text extraction succeeds
51
+ #[serde(default)]
52
+ pub force_ocr: bool,
53
+ /// Use async extraction (default: false for sync)
54
+ #[serde(default)]
55
+ pub r#async: bool,
56
+ }
57
+
58
+ /// Request parameters for batch file extraction.
59
+ #[derive(Debug, serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
60
+ pub struct BatchExtractFilesParams {
61
+ /// Paths to files to extract
62
+ pub paths: Vec<String>,
63
+ /// Enable OCR for scanned documents
64
+ #[serde(default)]
65
+ pub enable_ocr: bool,
66
+ /// Force OCR even if text extraction succeeds
67
+ #[serde(default)]
68
+ pub force_ocr: bool,
69
+ /// Use async extraction (default: false for sync)
70
+ #[serde(default)]
71
+ pub r#async: bool,
72
+ }
73
+
74
+ /// Request parameters for MIME type detection.
75
+ #[derive(Debug, serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
76
+ pub struct DetectMimeTypeParams {
77
+ /// Path to the file
78
+ pub path: String,
79
+ /// Use content-based detection (default: true)
80
+ #[serde(default = "default_use_content")]
81
+ pub use_content: bool,
82
+ }
83
+
84
+ fn default_use_content() -> bool {
85
+ true
86
+ }
87
+
88
+ /// Map Kreuzberg errors to MCP error responses with appropriate error codes.
89
+ ///
90
+ /// This function ensures different error types are properly differentiated in MCP responses:
91
+ /// - `Validation` errors → `INVALID_PARAMS` (-32602)
92
+ /// - `UnsupportedFormat` errors → `INVALID_PARAMS` (-32602)
93
+ /// - `Parsing` errors → `PARSE_ERROR` (-32700)
94
+ /// - `Io` errors → `INTERNAL_ERROR` (-32603) with context preserved
95
+ /// - All other errors → `INTERNAL_ERROR` (-32603)
96
+ ///
97
+ /// The error message and source chain are preserved to aid debugging.
98
+ #[doc(hidden)]
99
+ pub fn map_kreuzberg_error_to_mcp(error: KreuzbergError) -> McpError {
100
+ match error {
101
+ KreuzbergError::Validation { message, source } => {
102
+ let mut error_message = format!("Validation error: {}", message);
103
+ if let Some(src) = source {
104
+ error_message.push_str(&format!(" (caused by: {})", src));
105
+ }
106
+ McpError::invalid_params(error_message, None)
107
+ }
108
+
109
+ KreuzbergError::UnsupportedFormat(mime_type) => {
110
+ McpError::invalid_params(format!("Unsupported format: {}", mime_type), None)
111
+ }
112
+
113
+ KreuzbergError::MissingDependency(dep) => McpError::invalid_params(
114
+ format!(
115
+ "Missing required dependency: {}. Please install it to use this feature.",
116
+ dep
117
+ ),
118
+ None,
119
+ ),
120
+
121
+ KreuzbergError::Parsing { message, source } => {
122
+ let mut error_message = format!("Parsing error: {}", message);
123
+ if let Some(src) = source {
124
+ error_message.push_str(&format!(" (caused by: {})", src));
125
+ }
126
+ McpError::parse_error(error_message, None)
127
+ }
128
+
129
+ // OSError/RuntimeError must bubble up - system errors need user reports ~keep
130
+ KreuzbergError::Io(io_err) => McpError::internal_error(format!("System I/O error: {}", io_err), None),
131
+
132
+ KreuzbergError::Ocr { message, source } => {
133
+ let mut error_message = format!("OCR processing error: {}", message);
134
+ if let Some(src) = source {
135
+ error_message.push_str(&format!(" (caused by: {})", src));
136
+ }
137
+ McpError::internal_error(error_message, None)
138
+ }
139
+
140
+ KreuzbergError::Cache { message, source } => {
141
+ let mut error_message = format!("Cache error: {}", message);
142
+ if let Some(src) = source {
143
+ error_message.push_str(&format!(" (caused by: {})", src));
144
+ }
145
+ McpError::internal_error(error_message, None)
146
+ }
147
+
148
+ KreuzbergError::ImageProcessing { message, source } => {
149
+ let mut error_message = format!("Image processing error: {}", message);
150
+ if let Some(src) = source {
151
+ error_message.push_str(&format!(" (caused by: {})", src));
152
+ }
153
+ McpError::internal_error(error_message, None)
154
+ }
155
+
156
+ KreuzbergError::Serialization { message, source } => {
157
+ let mut error_message = format!("Serialization error: {}", message);
158
+ if let Some(src) = source {
159
+ error_message.push_str(&format!(" (caused by: {})", src));
160
+ }
161
+ McpError::internal_error(error_message, None)
162
+ }
163
+
164
+ KreuzbergError::Plugin { message, plugin_name } => {
165
+ McpError::internal_error(format!("Plugin '{}' error: {}", plugin_name, message), None)
166
+ }
167
+
168
+ KreuzbergError::LockPoisoned(msg) => McpError::internal_error(format!("Internal lock poisoned: {}", msg), None),
169
+
170
+ KreuzbergError::Other(msg) => McpError::internal_error(msg, None),
171
+ }
172
+ }
173
+
174
+ /// Kreuzberg MCP server.
175
+ ///
176
+ /// Provides document extraction capabilities via MCP tools.
177
+ ///
178
+ /// The server loads a default extraction configuration from kreuzberg.toml/yaml/json
179
+ /// via discovery. Per-request OCR settings override the defaults.
180
+ #[derive(Clone)]
181
+ pub struct KreuzbergMcp {
182
+ tool_router: ToolRouter<KreuzbergMcp>,
183
+ /// Default extraction configuration loaded from config file via discovery
184
+ default_config: std::sync::Arc<ExtractionConfig>,
185
+ }
186
+
187
+ #[tool_router]
188
+ impl KreuzbergMcp {
189
+ /// Create a new Kreuzberg MCP server instance with default config.
190
+ ///
191
+ /// Uses `ExtractionConfig::discover()` to search for kreuzberg.toml/yaml/json
192
+ /// in current and parent directories. Falls back to default configuration if
193
+ /// no config file is found.
194
+ #[allow(clippy::manual_unwrap_or_default)]
195
+ pub fn new() -> crate::Result<Self> {
196
+ let config = match ExtractionConfig::discover()? {
197
+ Some(config) => {
198
+ #[cfg(feature = "api")]
199
+ tracing::info!("Loaded extraction config from discovered file");
200
+ config
201
+ }
202
+ None => {
203
+ #[cfg(feature = "api")]
204
+ tracing::info!("No config file found, using default configuration");
205
+ ExtractionConfig::default()
206
+ }
207
+ };
208
+
209
+ Ok(Self::with_config(config))
210
+ }
211
+
212
+ /// Create a new Kreuzberg MCP server instance with explicit config.
213
+ ///
214
+ /// # Arguments
215
+ ///
216
+ /// * `config` - Default extraction configuration for all tool calls
217
+ pub fn with_config(config: ExtractionConfig) -> Self {
218
+ Self {
219
+ tool_router: Self::tool_router(),
220
+ default_config: std::sync::Arc::new(config),
221
+ }
222
+ }
223
+
224
+ /// Extract content from a file.
225
+ ///
226
+ /// This tool extracts text, metadata, and tables from documents in various formats
227
+ /// including PDFs, Word documents, Excel spreadsheets, images (with OCR), and more.
228
+ #[tool(
229
+ description = "Extract content from a file by path. Supports PDFs, Word, Excel, images (with OCR), HTML, and more."
230
+ )]
231
+ async fn extract_file(
232
+ &self,
233
+ Parameters(params): Parameters<ExtractFileParams>,
234
+ ) -> Result<CallToolResult, McpError> {
235
+ let config = build_config(&self.default_config, params.enable_ocr, params.force_ocr);
236
+
237
+ let result = if params.r#async {
238
+ extract_file(&params.path, params.mime_type.as_deref(), &config)
239
+ .await
240
+ .map_err(map_kreuzberg_error_to_mcp)?
241
+ } else {
242
+ extract_file_sync(&params.path, params.mime_type.as_deref(), &config).map_err(map_kreuzberg_error_to_mcp)?
243
+ };
244
+
245
+ let response = format_extraction_result(&result);
246
+ Ok(CallToolResult::success(vec![Content::text(response)]))
247
+ }
248
+
249
+ /// Extract content from base64-encoded bytes.
250
+ ///
251
+ /// This tool extracts text, metadata, and tables from base64-encoded document data.
252
+ #[tool(
253
+ description = "Extract content from base64-encoded file data. Returns extracted text, metadata, and tables."
254
+ )]
255
+ async fn extract_bytes(
256
+ &self,
257
+ Parameters(params): Parameters<ExtractBytesParams>,
258
+ ) -> Result<CallToolResult, McpError> {
259
+ let bytes = BASE64_STANDARD
260
+ .decode(&params.data)
261
+ .map_err(|e| McpError::invalid_params(format!("Invalid base64: {}", e), None))?;
262
+
263
+ let config = build_config(&self.default_config, params.enable_ocr, params.force_ocr);
264
+
265
+ let mime_type = params.mime_type.as_deref().unwrap_or("");
266
+
267
+ let result = if params.r#async {
268
+ extract_bytes(&bytes, mime_type, &config)
269
+ .await
270
+ .map_err(map_kreuzberg_error_to_mcp)?
271
+ } else {
272
+ extract_bytes_sync(&bytes, mime_type, &config).map_err(map_kreuzberg_error_to_mcp)?
273
+ };
274
+
275
+ let response = format_extraction_result(&result);
276
+ Ok(CallToolResult::success(vec![Content::text(response)]))
277
+ }
278
+
279
+ /// Extract content from multiple files in parallel.
280
+ ///
281
+ /// This tool efficiently processes multiple documents simultaneously, useful for batch operations.
282
+ #[tool(description = "Extract content from multiple files in parallel. Returns results for all files.")]
283
+ async fn batch_extract_files(
284
+ &self,
285
+ Parameters(params): Parameters<BatchExtractFilesParams>,
286
+ ) -> Result<CallToolResult, McpError> {
287
+ let config = build_config(&self.default_config, params.enable_ocr, params.force_ocr);
288
+
289
+ let results = if params.r#async {
290
+ batch_extract_file(params.paths.clone(), &config)
291
+ .await
292
+ .map_err(map_kreuzberg_error_to_mcp)?
293
+ } else {
294
+ batch_extract_file_sync(params.paths.clone(), &config).map_err(map_kreuzberg_error_to_mcp)?
295
+ };
296
+
297
+ let mut response = String::new();
298
+ for (i, result) in results.iter().enumerate() {
299
+ response.push_str(&format!("=== Document {}: {} ===\n", i + 1, params.paths[i]));
300
+ response.push_str(&format_extraction_result(result));
301
+ response.push_str("\n\n");
302
+ }
303
+
304
+ Ok(CallToolResult::success(vec![Content::text(response)]))
305
+ }
306
+
307
+ /// Detect the MIME type of a file.
308
+ ///
309
+ /// This tool identifies the file format, useful for determining which extractor to use.
310
+ #[tool(description = "Detect the MIME type of a file. Returns the detected MIME type string.")]
311
+ fn detect_mime_type(
312
+ &self,
313
+ Parameters(params): Parameters<DetectMimeTypeParams>,
314
+ ) -> Result<CallToolResult, McpError> {
315
+ let mime_type = detect_mime_type(&params.path, params.use_content).map_err(map_kreuzberg_error_to_mcp)?;
316
+
317
+ Ok(CallToolResult::success(vec![Content::text(mime_type)]))
318
+ }
319
+
320
+ /// Get cache statistics.
321
+ ///
322
+ /// This tool returns statistics about the cache including total files, size, and disk space.
323
+ #[tool(description = "Get cache statistics including total files, size, and available disk space.")]
324
+ fn cache_stats(&self, Parameters(_): Parameters<()>) -> Result<CallToolResult, McpError> {
325
+ let cache_dir = std::env::current_dir()
326
+ .unwrap_or_else(|_| std::path::PathBuf::from("."))
327
+ .join(".kreuzberg");
328
+
329
+ let stats = cache::get_cache_metadata(cache_dir.to_str().unwrap_or(".")).map_err(map_kreuzberg_error_to_mcp)?;
330
+
331
+ let response = format!(
332
+ "Cache Statistics\n\
333
+ ================\n\
334
+ Directory: {}\n\
335
+ Total files: {}\n\
336
+ Total size: {:.2} MB\n\
337
+ Available space: {:.2} MB\n\
338
+ Oldest file age: {:.2} days\n\
339
+ Newest file age: {:.2} days",
340
+ cache_dir.to_string_lossy(),
341
+ stats.total_files,
342
+ stats.total_size_mb,
343
+ stats.available_space_mb,
344
+ stats.oldest_file_age_days,
345
+ stats.newest_file_age_days
346
+ );
347
+
348
+ Ok(CallToolResult::success(vec![Content::text(response)]))
349
+ }
350
+
351
+ /// Clear the cache.
352
+ ///
353
+ /// This tool removes all cached files and returns the number of files removed and space freed.
354
+ #[tool(description = "Clear all cached files. Returns the number of files removed and space freed in MB.")]
355
+ fn cache_clear(&self, Parameters(_): Parameters<()>) -> Result<CallToolResult, McpError> {
356
+ let cache_dir = std::env::current_dir()
357
+ .unwrap_or_else(|_| std::path::PathBuf::from("."))
358
+ .join(".kreuzberg");
359
+
360
+ let (removed_files, freed_mb) =
361
+ cache::clear_cache_directory(cache_dir.to_str().unwrap_or(".")).map_err(map_kreuzberg_error_to_mcp)?;
362
+
363
+ let response = format!(
364
+ "Cache cleared successfully\n\
365
+ Directory: {}\n\
366
+ Removed files: {}\n\
367
+ Freed space: {:.2} MB",
368
+ cache_dir.to_string_lossy(),
369
+ removed_files,
370
+ freed_mb
371
+ );
372
+
373
+ Ok(CallToolResult::success(vec![Content::text(response)]))
374
+ }
375
+ }
376
+
377
+ #[tool_handler]
378
+ impl ServerHandler for KreuzbergMcp {
379
+ fn get_info(&self) -> ServerInfo {
380
+ ServerInfo {
381
+ protocol_version: ProtocolVersion::default(),
382
+ capabilities: ServerCapabilities {
383
+ tools: Some(ToolsCapability::default()),
384
+ ..Default::default()
385
+ },
386
+ server_info: Implementation {
387
+ name: "kreuzberg-mcp".to_string(),
388
+ title: Some("Kreuzberg Document Intelligence MCP Server".to_string()),
389
+ version: env!("CARGO_PKG_VERSION").to_string(),
390
+ icons: None,
391
+ website_url: Some("https://goldziher.github.io/kreuzberg/".to_string()),
392
+ },
393
+ instructions: Some(
394
+ "Extract content from documents in various formats. Supports PDFs, Word documents, \
395
+ Excel spreadsheets, images (with OCR), HTML, emails, and more. Use enable_ocr=true \
396
+ for scanned documents, force_ocr=true to always use OCR even if text extraction \
397
+ succeeds."
398
+ .to_string(),
399
+ ),
400
+ }
401
+ }
402
+ }
403
+
404
+ impl Default for KreuzbergMcp {
405
+ fn default() -> Self {
406
+ Self::new().unwrap_or_else(|e| {
407
+ #[cfg(feature = "api")]
408
+ tracing::warn!("Failed to discover config, using default: {}", e);
409
+ #[cfg(not(feature = "api"))]
410
+ tracing::debug!("Warning: Failed to discover config, using default: {}", e);
411
+ Self::with_config(ExtractionConfig::default())
412
+ })
413
+ }
414
+ }
415
+
416
+ /// Start the Kreuzberg MCP server.
417
+ ///
418
+ /// This function initializes and runs the MCP server using stdio transport.
419
+ /// It will block until the server is shut down.
420
+ ///
421
+ /// # Errors
422
+ ///
423
+ /// Returns an error if the server fails to start or encounters a fatal error.
424
+ ///
425
+ /// # Example
426
+ ///
427
+ /// ```rust,no_run
428
+ /// use kreuzberg::mcp::start_mcp_server;
429
+ ///
430
+ /// #[tokio::main]
431
+ /// async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
432
+ /// start_mcp_server().await?;
433
+ /// Ok(())
434
+ /// }
435
+ /// ```
436
+ pub async fn start_mcp_server() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
437
+ let service = KreuzbergMcp::new()?.serve(stdio()).await?;
438
+
439
+ service.waiting().await?;
440
+ Ok(())
441
+ }
442
+
443
+ /// Start MCP server with custom extraction config.
444
+ ///
445
+ /// This variant allows specifying a custom extraction configuration
446
+ /// (e.g., loaded from a file) instead of using defaults.
447
+ pub async fn start_mcp_server_with_config(
448
+ config: ExtractionConfig,
449
+ ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
450
+ let service = KreuzbergMcp::with_config(config).serve(stdio()).await?;
451
+
452
+ service.waiting().await?;
453
+ Ok(())
454
+ }
455
+
456
+ /// Build extraction config from MCP parameters.
457
+ ///
458
+ /// Starts with the default config and overlays OCR settings from request parameters.
459
+ fn build_config(default_config: &ExtractionConfig, enable_ocr: bool, force_ocr: bool) -> ExtractionConfig {
460
+ let mut config = default_config.clone();
461
+
462
+ config.ocr = if enable_ocr {
463
+ Some(crate::OcrConfig {
464
+ backend: "tesseract".to_string(),
465
+ language: "eng".to_string(),
466
+ tesseract_config: None,
467
+ })
468
+ } else {
469
+ None
470
+ };
471
+ config.force_ocr = force_ocr;
472
+
473
+ config
474
+ }
475
+
476
+ /// Format extraction result as human-readable text.
477
+ fn format_extraction_result(result: &KreuzbergResult) -> String {
478
+ let mut response = String::new();
479
+
480
+ response.push_str(&format!("Content ({} characters):\n", result.content.len()));
481
+ response.push_str(&result.content);
482
+ response.push_str("\n\n");
483
+
484
+ response.push_str("Metadata:\n");
485
+ response.push_str(&serde_json::to_string_pretty(&result.metadata).unwrap_or_default());
486
+ response.push_str("\n\n");
487
+
488
+ if !result.tables.is_empty() {
489
+ response.push_str(&format!("Tables ({}):\n", result.tables.len()));
490
+ for (i, table) in result.tables.iter().enumerate() {
491
+ response.push_str(&format!("\nTable {} (page {}):\n", i + 1, table.page_number));
492
+ response.push_str(&table.markdown);
493
+ response.push('\n');
494
+ }
495
+ }
496
+
497
+ response
498
+ }
499
+
500
+ #[cfg(test)]
501
+ mod tests {
502
+ use super::*;
503
+ use std::path::PathBuf;
504
+
505
+ /// Get the path to a test document relative to workspace root.
506
+ fn get_test_path(relative_path: &str) -> String {
507
+ let workspace_root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
508
+ .parent()
509
+ .unwrap()
510
+ .parent()
511
+ .unwrap()
512
+ .to_path_buf();
513
+
514
+ workspace_root
515
+ .join("test_documents")
516
+ .join(relative_path)
517
+ .to_string_lossy()
518
+ .to_string()
519
+ }
520
+
521
+ #[tokio::test]
522
+ async fn test_tool_router_has_routes() {
523
+ let router = KreuzbergMcp::tool_router();
524
+ assert!(router.has_route("extract_file"));
525
+ assert!(router.has_route("extract_bytes"));
526
+ assert!(router.has_route("batch_extract_files"));
527
+ assert!(router.has_route("detect_mime_type"));
528
+ assert!(router.has_route("cache_stats"));
529
+ assert!(router.has_route("cache_clear"));
530
+
531
+ let tools = router.list_all();
532
+ assert_eq!(tools.len(), 6);
533
+ }
534
+
535
+ #[test]
536
+ fn test_server_info() {
537
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
538
+ let info = server.get_info();
539
+
540
+ assert_eq!(info.server_info.name, "kreuzberg-mcp");
541
+ assert_eq!(info.server_info.version, env!("CARGO_PKG_VERSION"));
542
+ assert!(info.capabilities.tools.is_some());
543
+ }
544
+
545
+ #[test]
546
+ fn test_build_config() {
547
+ let default_config = ExtractionConfig::default();
548
+
549
+ let config = build_config(&default_config, false, false);
550
+ assert!(config.ocr.is_none());
551
+ assert!(!config.force_ocr);
552
+
553
+ let config = build_config(&default_config, true, false);
554
+ assert!(config.ocr.is_some());
555
+ assert!(!config.force_ocr);
556
+
557
+ let config = build_config(&default_config, true, true);
558
+ assert!(config.ocr.is_some());
559
+ assert!(config.force_ocr);
560
+ }
561
+
562
+ #[test]
563
+ fn test_with_config_stores_provided_config() {
564
+ let custom_config = ExtractionConfig {
565
+ force_ocr: true,
566
+ use_cache: false,
567
+ ..Default::default()
568
+ };
569
+
570
+ let server = KreuzbergMcp::with_config(custom_config);
571
+
572
+ assert!(server.default_config.force_ocr);
573
+ assert!(!server.default_config.use_cache);
574
+ }
575
+
576
+ #[test]
577
+ fn test_map_validation_error_to_invalid_params() {
578
+ let error = KreuzbergError::validation("invalid file path");
579
+ let mcp_error = map_kreuzberg_error_to_mcp(error);
580
+
581
+ assert_eq!(mcp_error.code.0, -32602);
582
+ assert!(mcp_error.message.contains("Validation error"));
583
+ assert!(mcp_error.message.contains("invalid file path"));
584
+ }
585
+
586
+ #[test]
587
+ fn test_map_validation_error_with_source_preserves_chain() {
588
+ let source = std::io::Error::new(std::io::ErrorKind::InvalidInput, "bad param");
589
+ let error = KreuzbergError::validation_with_source("invalid configuration", source);
590
+ let mcp_error = map_kreuzberg_error_to_mcp(error);
591
+
592
+ assert_eq!(mcp_error.code.0, -32602);
593
+ assert!(mcp_error.message.contains("Validation error"));
594
+ assert!(mcp_error.message.contains("invalid configuration"));
595
+ assert!(mcp_error.message.contains("caused by"));
596
+ }
597
+
598
+ #[test]
599
+ fn test_map_unsupported_format_to_invalid_params() {
600
+ let error = KreuzbergError::UnsupportedFormat("application/unknown".to_string());
601
+ let mcp_error = map_kreuzberg_error_to_mcp(error);
602
+
603
+ assert_eq!(mcp_error.code.0, -32602);
604
+ assert!(mcp_error.message.contains("Unsupported format"));
605
+ assert!(mcp_error.message.contains("application/unknown"));
606
+ }
607
+
608
+ #[test]
609
+ fn test_map_missing_dependency_to_invalid_params() {
610
+ let error = KreuzbergError::MissingDependency("tesseract".to_string());
611
+ let mcp_error = map_kreuzberg_error_to_mcp(error);
612
+
613
+ assert_eq!(mcp_error.code.0, -32602);
614
+ assert!(mcp_error.message.contains("Missing required dependency"));
615
+ assert!(mcp_error.message.contains("tesseract"));
616
+ assert!(mcp_error.message.contains("Please install"));
617
+ }
618
+
619
+ #[test]
620
+ fn test_map_parsing_error_to_parse_error() {
621
+ let error = KreuzbergError::parsing("corrupt PDF file");
622
+ let mcp_error = map_kreuzberg_error_to_mcp(error);
623
+
624
+ assert_eq!(mcp_error.code.0, -32700);
625
+ assert!(mcp_error.message.contains("Parsing error"));
626
+ assert!(mcp_error.message.contains("corrupt PDF file"));
627
+ }
628
+
629
+ #[test]
630
+ fn test_map_parsing_error_with_source_preserves_chain() {
631
+ let source = std::io::Error::new(std::io::ErrorKind::InvalidData, "malformed data");
632
+ let error = KreuzbergError::parsing_with_source("failed to parse document", source);
633
+ let mcp_error = map_kreuzberg_error_to_mcp(error);
634
+
635
+ assert_eq!(mcp_error.code.0, -32700);
636
+ assert!(mcp_error.message.contains("Parsing error"));
637
+ assert!(mcp_error.message.contains("failed to parse document"));
638
+ assert!(mcp_error.message.contains("caused by"));
639
+ }
640
+
641
+ #[test]
642
+ fn test_map_io_error_to_internal_error() {
643
+ let io_error = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
644
+ let error = KreuzbergError::Io(io_error);
645
+ let mcp_error = map_kreuzberg_error_to_mcp(error);
646
+
647
+ assert_eq!(mcp_error.code.0, -32603);
648
+ assert!(mcp_error.message.contains("System I/O error"));
649
+ assert!(mcp_error.message.contains("file not found"));
650
+ }
651
+
652
+ #[test]
653
+ fn test_map_ocr_error_to_internal_error() {
654
+ let error = KreuzbergError::ocr("tesseract failed");
655
+ let mcp_error = map_kreuzberg_error_to_mcp(error);
656
+
657
+ assert_eq!(mcp_error.code.0, -32603);
658
+ assert!(mcp_error.message.contains("OCR processing error"));
659
+ assert!(mcp_error.message.contains("tesseract failed"));
660
+ }
661
+
662
+ #[test]
663
+ fn test_map_cache_error_to_internal_error() {
664
+ let error = KreuzbergError::cache("cache write failed");
665
+ let mcp_error = map_kreuzberg_error_to_mcp(error);
666
+
667
+ assert_eq!(mcp_error.code.0, -32603);
668
+ assert!(mcp_error.message.contains("Cache error"));
669
+ assert!(mcp_error.message.contains("cache write failed"));
670
+ }
671
+
672
+ #[test]
673
+ fn test_map_image_processing_error_to_internal_error() {
674
+ let error = KreuzbergError::image_processing("resize failed");
675
+ let mcp_error = map_kreuzberg_error_to_mcp(error);
676
+
677
+ assert_eq!(mcp_error.code.0, -32603);
678
+ assert!(mcp_error.message.contains("Image processing error"));
679
+ assert!(mcp_error.message.contains("resize failed"));
680
+ }
681
+
682
+ #[test]
683
+ fn test_map_serialization_error_to_internal_error() {
684
+ let error = KreuzbergError::serialization("JSON encode failed");
685
+ let mcp_error = map_kreuzberg_error_to_mcp(error);
686
+
687
+ assert_eq!(mcp_error.code.0, -32603);
688
+ assert!(mcp_error.message.contains("Serialization error"));
689
+ assert!(mcp_error.message.contains("JSON encode failed"));
690
+ }
691
+
692
+ #[test]
693
+ fn test_map_plugin_error_to_internal_error() {
694
+ let error = KreuzbergError::Plugin {
695
+ message: "extraction failed".to_string(),
696
+ plugin_name: "pdf-extractor".to_string(),
697
+ };
698
+ let mcp_error = map_kreuzberg_error_to_mcp(error);
699
+
700
+ assert_eq!(mcp_error.code.0, -32603);
701
+ assert!(mcp_error.message.contains("Plugin 'pdf-extractor' error"));
702
+ assert!(mcp_error.message.contains("extraction failed"));
703
+ }
704
+
705
+ #[test]
706
+ fn test_map_lock_poisoned_error_to_internal_error() {
707
+ let error = KreuzbergError::LockPoisoned("registry lock poisoned".to_string());
708
+ let mcp_error = map_kreuzberg_error_to_mcp(error);
709
+
710
+ assert_eq!(mcp_error.code.0, -32603);
711
+ assert!(mcp_error.message.contains("Internal lock poisoned"));
712
+ assert!(mcp_error.message.contains("registry lock poisoned"));
713
+ }
714
+
715
+ #[test]
716
+ fn test_map_other_error_to_internal_error() {
717
+ let error = KreuzbergError::Other("unexpected error".to_string());
718
+ let mcp_error = map_kreuzberg_error_to_mcp(error);
719
+
720
+ assert_eq!(mcp_error.code.0, -32603);
721
+ assert!(mcp_error.message.contains("unexpected error"));
722
+ }
723
+
724
+ #[test]
725
+ fn test_error_type_differentiation() {
726
+ let validation = KreuzbergError::validation("test");
727
+ let parsing = KreuzbergError::parsing("test");
728
+ let io = KreuzbergError::Io(std::io::Error::other("test"));
729
+
730
+ let val_mcp = map_kreuzberg_error_to_mcp(validation);
731
+ let parse_mcp = map_kreuzberg_error_to_mcp(parsing);
732
+ let io_mcp = map_kreuzberg_error_to_mcp(io);
733
+
734
+ assert_eq!(val_mcp.code.0, -32602);
735
+ assert_eq!(parse_mcp.code.0, -32700);
736
+ assert_eq!(io_mcp.code.0, -32603);
737
+
738
+ assert_ne!(val_mcp.code.0, parse_mcp.code.0);
739
+ assert_ne!(val_mcp.code.0, io_mcp.code.0);
740
+ assert_ne!(parse_mcp.code.0, io_mcp.code.0);
741
+ }
742
+
743
+ #[test]
744
+ fn test_format_extraction_result_with_content() {
745
+ let result = KreuzbergResult {
746
+ content: "Sample extracted text".to_string(),
747
+ mime_type: "text/plain".to_string(),
748
+ metadata: crate::Metadata::default(),
749
+ tables: vec![],
750
+ detected_languages: None,
751
+ chunks: None,
752
+ images: None,
753
+ };
754
+
755
+ let formatted = format_extraction_result(&result);
756
+
757
+ assert!(formatted.contains("Content (21 characters)"));
758
+ assert!(formatted.contains("Sample extracted text"));
759
+ assert!(formatted.contains("Metadata:"));
760
+ }
761
+
762
+ #[test]
763
+ fn test_format_extraction_result_with_tables() {
764
+ let result = KreuzbergResult {
765
+ content: "Document with tables".to_string(),
766
+ mime_type: "application/pdf".to_string(),
767
+ metadata: crate::Metadata::default(),
768
+ tables: vec![
769
+ crate::Table {
770
+ cells: vec![
771
+ vec!["Col1".to_string(), "Col2".to_string()],
772
+ vec!["A".to_string(), "B".to_string()],
773
+ ],
774
+ page_number: 1,
775
+ markdown: "| Col1 | Col2 |\n|------|------|\n| A | B |".to_string(),
776
+ },
777
+ crate::Table {
778
+ cells: vec![
779
+ vec!["X".to_string(), "Y".to_string()],
780
+ vec!["1".to_string(), "2".to_string()],
781
+ ],
782
+ page_number: 2,
783
+ markdown: "| X | Y |\n|---|---|\n| 1 | 2 |".to_string(),
784
+ },
785
+ ],
786
+ detected_languages: None,
787
+ chunks: None,
788
+ images: None,
789
+ };
790
+
791
+ let formatted = format_extraction_result(&result);
792
+
793
+ assert!(formatted.contains("Tables (2)"));
794
+ assert!(formatted.contains("Table 1 (page 1)"));
795
+ assert!(formatted.contains("Table 2 (page 2)"));
796
+ assert!(formatted.contains("| Col1 | Col2 |"));
797
+ assert!(formatted.contains("| X | Y |"));
798
+ }
799
+
800
+ #[test]
801
+ fn test_format_extraction_result_empty_content() {
802
+ let result = KreuzbergResult {
803
+ content: String::new(),
804
+ mime_type: "text/plain".to_string(),
805
+ metadata: crate::Metadata::default(),
806
+ tables: vec![],
807
+ detected_languages: None,
808
+ chunks: None,
809
+ images: None,
810
+ };
811
+
812
+ let formatted = format_extraction_result(&result);
813
+
814
+ assert!(formatted.contains("Content (0 characters)"));
815
+ assert!(formatted.contains("Metadata:"));
816
+ }
817
+
818
+ #[test]
819
+ fn test_format_extraction_result_no_tables() {
820
+ let result = KreuzbergResult {
821
+ content: "Simple text".to_string(),
822
+ mime_type: "text/plain".to_string(),
823
+ metadata: crate::Metadata::default(),
824
+ tables: vec![],
825
+ detected_languages: None,
826
+ chunks: None,
827
+ images: None,
828
+ };
829
+
830
+ let formatted = format_extraction_result(&result);
831
+
832
+ assert!(formatted.contains("Simple text"));
833
+ assert!(!formatted.contains("Tables"));
834
+ }
835
+
836
+ #[tokio::test]
837
+ async fn test_extract_file_sync_with_valid_pdf() {
838
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
839
+ let params = ExtractFileParams {
840
+ path: get_test_path("pdfs_with_tables/tiny.pdf").to_string(),
841
+ mime_type: None,
842
+ enable_ocr: false,
843
+ force_ocr: false,
844
+ r#async: true,
845
+ };
846
+
847
+ let result = server.extract_file(Parameters(params)).await;
848
+
849
+ assert!(result.is_ok());
850
+ let call_result = result.unwrap();
851
+ if let Some(content) = call_result.content.first() {
852
+ match &content.raw {
853
+ RawContent::Text(text) => {
854
+ assert!(!text.text.is_empty());
855
+ assert!(text.text.contains("Content"));
856
+ }
857
+ _ => panic!("Expected text content"),
858
+ }
859
+ } else {
860
+ panic!("Expected content in result");
861
+ }
862
+ }
863
+
864
+ #[tokio::test]
865
+ async fn test_extract_file_async_with_valid_pdf() {
866
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
867
+ let params = ExtractFileParams {
868
+ path: get_test_path("pdfs_with_tables/tiny.pdf").to_string(),
869
+ mime_type: None,
870
+ enable_ocr: false,
871
+ force_ocr: false,
872
+ r#async: true,
873
+ };
874
+
875
+ let result = server.extract_file(Parameters(params)).await;
876
+
877
+ assert!(result.is_ok());
878
+ let call_result = result.unwrap();
879
+ if let Some(content) = call_result.content.first() {
880
+ match &content.raw {
881
+ RawContent::Text(text) => {
882
+ assert!(!text.text.is_empty());
883
+ }
884
+ _ => panic!("Expected text content"),
885
+ }
886
+ } else {
887
+ panic!("Expected content in result");
888
+ }
889
+ }
890
+
891
+ #[tokio::test]
892
+ async fn test_extract_file_with_invalid_path() {
893
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
894
+ let params = ExtractFileParams {
895
+ path: "/nonexistent/file.pdf".to_string(),
896
+ mime_type: None,
897
+ enable_ocr: false,
898
+ force_ocr: false,
899
+ r#async: true,
900
+ };
901
+
902
+ let result = server.extract_file(Parameters(params)).await;
903
+
904
+ assert!(result.is_err());
905
+ let error = result.unwrap_err();
906
+ assert!(error.code.0 == -32602 || error.code.0 == -32603);
907
+ }
908
+
909
+ #[tokio::test]
910
+ async fn test_extract_file_with_mime_type_hint() {
911
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
912
+ let params = ExtractFileParams {
913
+ path: get_test_path("pdfs_with_tables/tiny.pdf").to_string(),
914
+ mime_type: Some("application/pdf".to_string()),
915
+ enable_ocr: false,
916
+ force_ocr: false,
917
+ r#async: true,
918
+ };
919
+
920
+ let result = server.extract_file(Parameters(params)).await;
921
+
922
+ assert!(result.is_ok());
923
+ }
924
+
925
+ #[tokio::test]
926
+ async fn test_extract_file_with_ocr_enabled() {
927
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
928
+ let params = ExtractFileParams {
929
+ path: get_test_path("pdfs_with_tables/tiny.pdf").to_string(),
930
+ mime_type: None,
931
+ enable_ocr: true,
932
+ force_ocr: false,
933
+ r#async: true,
934
+ };
935
+
936
+ let result = server.extract_file(Parameters(params)).await;
937
+
938
+ assert!(result.is_ok() || result.is_err());
939
+ }
940
+
941
+ #[tokio::test]
942
+ async fn test_extract_file_with_force_ocr() {
943
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
944
+ let params = ExtractFileParams {
945
+ path: get_test_path("pdfs_with_tables/tiny.pdf").to_string(),
946
+ mime_type: None,
947
+ enable_ocr: true,
948
+ force_ocr: true,
949
+ r#async: true,
950
+ };
951
+
952
+ let result = server.extract_file(Parameters(params)).await;
953
+
954
+ assert!(result.is_ok() || result.is_err());
955
+ }
956
+
957
+ #[tokio::test]
958
+ async fn test_extract_bytes_sync_with_valid_data() {
959
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
960
+
961
+ let text_content = b"Hello, world!";
962
+ let encoded = BASE64_STANDARD.encode(text_content);
963
+
964
+ let params = ExtractBytesParams {
965
+ data: encoded,
966
+ mime_type: Some("text/plain".to_string()),
967
+ enable_ocr: false,
968
+ force_ocr: false,
969
+ r#async: true,
970
+ };
971
+
972
+ let result = server.extract_bytes(Parameters(params)).await;
973
+
974
+ assert!(result.is_ok());
975
+ let call_result = result.unwrap();
976
+ if let Some(content) = call_result.content.first() {
977
+ match &content.raw {
978
+ RawContent::Text(text) => {
979
+ assert!(text.text.contains("Hello, world!"));
980
+ }
981
+ _ => panic!("Expected text content"),
982
+ }
983
+ } else {
984
+ panic!("Expected content in result");
985
+ }
986
+ }
987
+
988
+ #[tokio::test]
989
+ async fn test_extract_bytes_async_with_valid_data() {
990
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
991
+
992
+ let text_content = b"Async extraction test";
993
+ let encoded = BASE64_STANDARD.encode(text_content);
994
+
995
+ let params = ExtractBytesParams {
996
+ data: encoded,
997
+ mime_type: Some("text/plain".to_string()),
998
+ enable_ocr: false,
999
+ force_ocr: false,
1000
+ r#async: true,
1001
+ };
1002
+
1003
+ let result = server.extract_bytes(Parameters(params)).await;
1004
+
1005
+ assert!(result.is_ok());
1006
+ }
1007
+
1008
+ #[tokio::test]
1009
+ async fn test_extract_bytes_with_invalid_base64() {
1010
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1011
+
1012
+ let params = ExtractBytesParams {
1013
+ data: "not-valid-base64!!!".to_string(),
1014
+ mime_type: None,
1015
+ enable_ocr: false,
1016
+ force_ocr: false,
1017
+ r#async: true,
1018
+ };
1019
+
1020
+ let result = server.extract_bytes(Parameters(params)).await;
1021
+
1022
+ assert!(result.is_err());
1023
+ let error = result.unwrap_err();
1024
+ assert_eq!(error.code.0, -32602);
1025
+ assert!(error.message.contains("Invalid base64"));
1026
+ }
1027
+
1028
+ #[tokio::test]
1029
+ async fn test_extract_bytes_without_mime_type() {
1030
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1031
+
1032
+ let text_content = b"Test content";
1033
+ let encoded = BASE64_STANDARD.encode(text_content);
1034
+
1035
+ let params = ExtractBytesParams {
1036
+ data: encoded,
1037
+ mime_type: None,
1038
+ enable_ocr: false,
1039
+ force_ocr: false,
1040
+ r#async: true,
1041
+ };
1042
+
1043
+ let result = server.extract_bytes(Parameters(params)).await;
1044
+
1045
+ assert!(result.is_ok() || result.is_err());
1046
+ }
1047
+
1048
+ #[tokio::test]
1049
+ async fn test_extract_bytes_with_ocr_enabled() {
1050
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1051
+
1052
+ let text_content = b"OCR test content";
1053
+ let encoded = BASE64_STANDARD.encode(text_content);
1054
+
1055
+ let params = ExtractBytesParams {
1056
+ data: encoded,
1057
+ mime_type: Some("text/plain".to_string()),
1058
+ enable_ocr: true,
1059
+ force_ocr: false,
1060
+ r#async: true,
1061
+ };
1062
+
1063
+ let result = server.extract_bytes(Parameters(params)).await;
1064
+
1065
+ assert!(result.is_ok() || result.is_err());
1066
+ }
1067
+
1068
+ #[tokio::test]
1069
+ async fn test_batch_extract_files_sync_with_valid_files() {
1070
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1071
+ let params = BatchExtractFilesParams {
1072
+ paths: vec![get_test_path("pdfs_with_tables/tiny.pdf").to_string()],
1073
+ enable_ocr: false,
1074
+ force_ocr: false,
1075
+ r#async: true,
1076
+ };
1077
+
1078
+ let result = server.batch_extract_files(Parameters(params)).await;
1079
+
1080
+ assert!(result.is_ok());
1081
+ let call_result = result.unwrap();
1082
+ if let Some(content) = call_result.content.first() {
1083
+ match &content.raw {
1084
+ RawContent::Text(text) => {
1085
+ assert!(text.text.contains("Document 1"));
1086
+ assert!(text.text.contains("tiny.pdf"));
1087
+ }
1088
+ _ => panic!("Expected text content"),
1089
+ }
1090
+ } else {
1091
+ panic!("Expected content in result");
1092
+ }
1093
+ }
1094
+
1095
+ #[tokio::test]
1096
+ async fn test_batch_extract_files_async_with_multiple_files() {
1097
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1098
+ let params = BatchExtractFilesParams {
1099
+ paths: vec![
1100
+ get_test_path("pdfs_with_tables/tiny.pdf").to_string(),
1101
+ get_test_path("pdfs_with_tables/medium.pdf").to_string(),
1102
+ ],
1103
+ enable_ocr: false,
1104
+ force_ocr: false,
1105
+ r#async: true,
1106
+ };
1107
+
1108
+ let result = server.batch_extract_files(Parameters(params)).await;
1109
+
1110
+ assert!(result.is_ok());
1111
+ let call_result = result.unwrap();
1112
+ if let Some(content) = call_result.content.first() {
1113
+ match &content.raw {
1114
+ RawContent::Text(text) => {
1115
+ assert!(text.text.contains("Document 1"));
1116
+ assert!(text.text.contains("Document 2"));
1117
+ }
1118
+ _ => panic!("Expected text content"),
1119
+ }
1120
+ } else {
1121
+ panic!("Expected content in result");
1122
+ }
1123
+ }
1124
+
1125
+ #[tokio::test]
1126
+ async fn test_batch_extract_files_with_empty_list() {
1127
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1128
+ let params = BatchExtractFilesParams {
1129
+ paths: vec![],
1130
+ enable_ocr: false,
1131
+ force_ocr: false,
1132
+ r#async: true,
1133
+ };
1134
+
1135
+ let result = server.batch_extract_files(Parameters(params)).await;
1136
+
1137
+ assert!(result.is_ok());
1138
+ let call_result = result.unwrap();
1139
+ if let Some(content) = call_result.content.first() {
1140
+ match &content.raw {
1141
+ RawContent::Text(text) => {
1142
+ assert!(text.text.is_empty() || text.text.trim().is_empty());
1143
+ }
1144
+ _ => panic!("Expected text content"),
1145
+ }
1146
+ } else {
1147
+ panic!("Expected content in result");
1148
+ }
1149
+ }
1150
+
1151
+ #[tokio::test]
1152
+ async fn test_batch_extract_files_with_invalid_file() {
1153
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1154
+ let params = BatchExtractFilesParams {
1155
+ paths: vec!["/nonexistent/file.pdf".to_string()],
1156
+ enable_ocr: false,
1157
+ force_ocr: false,
1158
+ r#async: true,
1159
+ };
1160
+
1161
+ let result = server.batch_extract_files(Parameters(params)).await;
1162
+
1163
+ assert!(result.is_ok() || result.is_err());
1164
+ }
1165
+
1166
+ #[tokio::test]
1167
+ async fn test_detect_mime_type_with_valid_file() {
1168
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1169
+ let params = DetectMimeTypeParams {
1170
+ path: get_test_path("pdfs_with_tables/tiny.pdf").to_string(),
1171
+ use_content: true,
1172
+ };
1173
+
1174
+ let result = server.detect_mime_type(Parameters(params));
1175
+
1176
+ assert!(result.is_ok());
1177
+ let call_result = result.unwrap();
1178
+ if let Some(content) = call_result.content.first() {
1179
+ match &content.raw {
1180
+ RawContent::Text(text) => {
1181
+ assert!(text.text.contains("application/pdf") || text.text.contains("pdf"));
1182
+ }
1183
+ _ => panic!("Expected text content"),
1184
+ }
1185
+ } else {
1186
+ panic!("Expected content in result");
1187
+ }
1188
+ }
1189
+
1190
+ #[tokio::test]
1191
+ async fn test_detect_mime_type_without_content_detection() {
1192
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1193
+ let params = DetectMimeTypeParams {
1194
+ path: get_test_path("pdfs_with_tables/tiny.pdf").to_string(),
1195
+ use_content: false,
1196
+ };
1197
+
1198
+ let result = server.detect_mime_type(Parameters(params));
1199
+
1200
+ assert!(result.is_ok());
1201
+ }
1202
+
1203
+ #[tokio::test]
1204
+ async fn test_detect_mime_type_with_invalid_file() {
1205
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1206
+ let params = DetectMimeTypeParams {
1207
+ path: "/nonexistent/file.pdf".to_string(),
1208
+ use_content: true,
1209
+ };
1210
+
1211
+ let result = server.detect_mime_type(Parameters(params));
1212
+
1213
+ assert!(result.is_err());
1214
+ let error = result.unwrap_err();
1215
+ assert!(error.code.0 == -32602 || error.code.0 == -32603);
1216
+ }
1217
+
1218
+ #[tokio::test]
1219
+ async fn test_cache_stats_returns_statistics() {
1220
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1221
+
1222
+ let result = server.cache_stats(Parameters(()));
1223
+
1224
+ assert!(result.is_ok());
1225
+ let call_result = result.unwrap();
1226
+ if let Some(content) = call_result.content.first() {
1227
+ match &content.raw {
1228
+ RawContent::Text(text) => {
1229
+ assert!(text.text.contains("Cache Statistics"));
1230
+ assert!(text.text.contains("Directory:"));
1231
+ assert!(text.text.contains("Total files:"));
1232
+ assert!(text.text.contains("Total size:"));
1233
+ assert!(text.text.contains("Available space:"));
1234
+ }
1235
+ _ => panic!("Expected text content"),
1236
+ }
1237
+ } else {
1238
+ panic!("Expected content in result");
1239
+ }
1240
+ }
1241
+
1242
+ #[tokio::test]
1243
+ async fn test_cache_clear_returns_result() {
1244
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1245
+
1246
+ let result = server.cache_clear(Parameters(()));
1247
+
1248
+ assert!(result.is_ok());
1249
+ let call_result = result.unwrap();
1250
+ if let Some(content) = call_result.content.first() {
1251
+ match &content.raw {
1252
+ RawContent::Text(text) => {
1253
+ assert!(text.text.contains("Cache cleared"));
1254
+ assert!(text.text.contains("Directory:"));
1255
+ assert!(text.text.contains("Removed files:"));
1256
+ assert!(text.text.contains("Freed space:"));
1257
+ }
1258
+ _ => panic!("Expected text content"),
1259
+ }
1260
+ } else {
1261
+ panic!("Expected content in result");
1262
+ }
1263
+ }
1264
+
1265
+ #[test]
1266
+ fn test_new_creates_server_with_default_config() {
1267
+ let server = KreuzbergMcp::new();
1268
+ assert!(server.is_ok());
1269
+ }
1270
+
1271
+ #[test]
1272
+ fn test_default_creates_server_without_panic() {
1273
+ let server = KreuzbergMcp::default();
1274
+ let info = server.get_info();
1275
+ assert_eq!(info.server_info.name, "kreuzberg-mcp");
1276
+ }
1277
+
1278
+ #[test]
1279
+ fn test_server_info_has_correct_fields() {
1280
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1281
+ let info = server.get_info();
1282
+
1283
+ assert_eq!(info.server_info.name, "kreuzberg-mcp");
1284
+ assert_eq!(
1285
+ info.server_info.title,
1286
+ Some("Kreuzberg Document Intelligence MCP Server".to_string())
1287
+ );
1288
+ assert_eq!(info.server_info.version, env!("CARGO_PKG_VERSION"));
1289
+ assert_eq!(
1290
+ info.server_info.website_url,
1291
+ Some("https://goldziher.github.io/kreuzberg/".to_string())
1292
+ );
1293
+ assert!(info.instructions.is_some());
1294
+ assert!(info.capabilities.tools.is_some());
1295
+ }
1296
+
1297
+ #[test]
1298
+ fn test_build_config_preserves_default_config_settings() {
1299
+ let default_config = ExtractionConfig {
1300
+ use_cache: false,
1301
+ ..Default::default()
1302
+ };
1303
+
1304
+ let config = build_config(&default_config, false, false);
1305
+
1306
+ assert!(!config.use_cache);
1307
+ }
1308
+
1309
+ #[test]
1310
+ fn test_build_config_ocr_disabled_by_default() {
1311
+ let default_config = ExtractionConfig::default();
1312
+
1313
+ let config = build_config(&default_config, false, false);
1314
+
1315
+ assert!(config.ocr.is_none());
1316
+ assert!(!config.force_ocr);
1317
+ }
1318
+
1319
+ #[test]
1320
+ fn test_build_config_ocr_enabled_creates_tesseract_config() {
1321
+ let default_config = ExtractionConfig::default();
1322
+
1323
+ let config = build_config(&default_config, true, false);
1324
+
1325
+ assert!(config.ocr.is_some());
1326
+ let ocr_config = config.ocr.unwrap();
1327
+ assert_eq!(ocr_config.backend, "tesseract");
1328
+ assert_eq!(ocr_config.language, "eng");
1329
+ }
1330
+
1331
+ #[test]
1332
+ fn test_extract_file_params_defaults() {
1333
+ let json = r#"{"path": "/test.pdf"}"#;
1334
+ let params: ExtractFileParams = serde_json::from_str(json).unwrap();
1335
+
1336
+ assert_eq!(params.path, "/test.pdf");
1337
+ assert_eq!(params.mime_type, None);
1338
+ assert!(!params.enable_ocr);
1339
+ assert!(!params.force_ocr);
1340
+ assert!(!params.r#async);
1341
+ }
1342
+
1343
+ #[test]
1344
+ fn test_extract_bytes_params_defaults() {
1345
+ let json = r#"{"data": "SGVsbG8="}"#;
1346
+ let params: ExtractBytesParams = serde_json::from_str(json).unwrap();
1347
+
1348
+ assert_eq!(params.data, "SGVsbG8=");
1349
+ assert_eq!(params.mime_type, None);
1350
+ assert!(!params.enable_ocr);
1351
+ assert!(!params.force_ocr);
1352
+ assert!(!params.r#async);
1353
+ }
1354
+
1355
+ #[test]
1356
+ fn test_batch_extract_files_params_defaults() {
1357
+ let json = r#"{"paths": ["/a.pdf", "/b.pdf"]}"#;
1358
+ let params: BatchExtractFilesParams = serde_json::from_str(json).unwrap();
1359
+
1360
+ assert_eq!(params.paths.len(), 2);
1361
+ assert!(!params.enable_ocr);
1362
+ assert!(!params.force_ocr);
1363
+ assert!(!params.r#async);
1364
+ }
1365
+
1366
+ #[test]
1367
+ fn test_detect_mime_type_params_defaults() {
1368
+ let json = r#"{"path": "/test.pdf"}"#;
1369
+ let params: DetectMimeTypeParams = serde_json::from_str(json).unwrap();
1370
+
1371
+ assert_eq!(params.path, "/test.pdf");
1372
+ assert!(params.use_content);
1373
+ }
1374
+
1375
+ #[test]
1376
+ fn test_detect_mime_type_params_use_content_false() {
1377
+ let json = r#"{"path": "/test.pdf", "use_content": false}"#;
1378
+ let params: DetectMimeTypeParams = serde_json::from_str(json).unwrap();
1379
+
1380
+ assert!(!params.use_content);
1381
+ }
1382
+
1383
+ #[test]
1384
+ fn test_mcp_server_info_protocol_version() {
1385
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1386
+ let info = server.get_info();
1387
+
1388
+ assert_eq!(info.protocol_version, ProtocolVersion::default());
1389
+ }
1390
+
1391
+ #[test]
1392
+ fn test_mcp_server_info_has_all_required_fields() {
1393
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1394
+ let info = server.get_info();
1395
+
1396
+ assert!(!info.server_info.name.is_empty());
1397
+ assert!(!info.server_info.version.is_empty());
1398
+
1399
+ assert!(info.server_info.title.is_some());
1400
+ assert!(info.server_info.website_url.is_some());
1401
+ assert!(info.instructions.is_some());
1402
+ }
1403
+
1404
+ #[test]
1405
+ fn test_mcp_server_capabilities_declares_tools() {
1406
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1407
+ let info = server.get_info();
1408
+
1409
+ assert!(info.capabilities.tools.is_some());
1410
+ }
1411
+
1412
+ #[test]
1413
+ fn test_mcp_server_name_follows_convention() {
1414
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1415
+ let info = server.get_info();
1416
+
1417
+ assert_eq!(info.server_info.name, "kreuzberg-mcp");
1418
+ assert!(!info.server_info.name.contains('_'));
1419
+ assert!(!info.server_info.name.contains(' '));
1420
+ }
1421
+
1422
+ #[test]
1423
+ fn test_mcp_version_matches_cargo_version() {
1424
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1425
+ let info = server.get_info();
1426
+
1427
+ assert_eq!(info.server_info.version, env!("CARGO_PKG_VERSION"));
1428
+ }
1429
+
1430
+ #[test]
1431
+ fn test_mcp_instructions_are_helpful() {
1432
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1433
+ let info = server.get_info();
1434
+
1435
+ let instructions = info.instructions.expect("Instructions should be present");
1436
+
1437
+ assert!(instructions.contains("extract") || instructions.contains("Extract"));
1438
+ assert!(instructions.contains("OCR") || instructions.contains("ocr"));
1439
+ assert!(instructions.contains("document"));
1440
+ }
1441
+
1442
+ #[tokio::test]
1443
+ async fn test_all_tools_are_registered() {
1444
+ let router = KreuzbergMcp::tool_router();
1445
+
1446
+ let expected_tools = vec![
1447
+ "extract_file",
1448
+ "extract_bytes",
1449
+ "batch_extract_files",
1450
+ "detect_mime_type",
1451
+ "cache_stats",
1452
+ "cache_clear",
1453
+ ];
1454
+
1455
+ for tool_name in expected_tools {
1456
+ assert!(router.has_route(tool_name), "Tool '{}' should be registered", tool_name);
1457
+ }
1458
+ }
1459
+
1460
+ #[tokio::test]
1461
+ async fn test_tool_count_is_correct() {
1462
+ let router = KreuzbergMcp::tool_router();
1463
+ let tools = router.list_all();
1464
+
1465
+ assert_eq!(tools.len(), 6, "Expected 6 tools, found {}", tools.len());
1466
+ }
1467
+
1468
+ #[tokio::test]
1469
+ async fn test_tools_have_descriptions() {
1470
+ let router = KreuzbergMcp::tool_router();
1471
+ let tools = router.list_all();
1472
+
1473
+ for tool in tools {
1474
+ assert!(
1475
+ tool.description.is_some(),
1476
+ "Tool '{}' should have a description",
1477
+ tool.name
1478
+ );
1479
+ let desc = tool.description.as_ref().unwrap();
1480
+ assert!(!desc.is_empty(), "Tool '{}' description should not be empty", tool.name);
1481
+ }
1482
+ }
1483
+
1484
+ #[tokio::test]
1485
+ async fn test_extract_file_tool_has_correct_schema() {
1486
+ let router = KreuzbergMcp::tool_router();
1487
+ let tools = router.list_all();
1488
+
1489
+ let extract_file_tool = tools
1490
+ .iter()
1491
+ .find(|t| t.name == "extract_file")
1492
+ .expect("extract_file tool should exist");
1493
+
1494
+ assert!(extract_file_tool.description.is_some());
1495
+
1496
+ assert!(!extract_file_tool.input_schema.is_empty());
1497
+ }
1498
+
1499
+ #[tokio::test]
1500
+ async fn test_all_tools_have_input_schemas() {
1501
+ let router = KreuzbergMcp::tool_router();
1502
+ let tools = router.list_all();
1503
+
1504
+ for tool in tools {
1505
+ assert!(
1506
+ !tool.input_schema.is_empty(),
1507
+ "Tool '{}' should have an input schema with fields",
1508
+ tool.name
1509
+ );
1510
+ }
1511
+ }
1512
+
1513
+ #[test]
1514
+ fn test_server_creation_with_custom_config() {
1515
+ let custom_config = ExtractionConfig {
1516
+ force_ocr: true,
1517
+ use_cache: false,
1518
+ ocr: Some(crate::OcrConfig {
1519
+ backend: "tesseract".to_string(),
1520
+ language: "spa".to_string(),
1521
+ tesseract_config: None,
1522
+ }),
1523
+ ..Default::default()
1524
+ };
1525
+
1526
+ let server = KreuzbergMcp::with_config(custom_config.clone());
1527
+
1528
+ assert_eq!(server.default_config.force_ocr, custom_config.force_ocr);
1529
+ assert_eq!(server.default_config.use_cache, custom_config.use_cache);
1530
+ }
1531
+
1532
+ #[test]
1533
+ fn test_server_clone_preserves_config() {
1534
+ let custom_config = ExtractionConfig {
1535
+ force_ocr: true,
1536
+ ..Default::default()
1537
+ };
1538
+
1539
+ let server1 = KreuzbergMcp::with_config(custom_config);
1540
+ let server2 = server1.clone();
1541
+
1542
+ assert_eq!(server1.default_config.force_ocr, server2.default_config.force_ocr);
1543
+ }
1544
+
1545
+ #[tokio::test]
1546
+ async fn test_extract_bytes_with_empty_data() {
1547
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1548
+
1549
+ let params = ExtractBytesParams {
1550
+ data: String::new(),
1551
+ mime_type: Some("text/plain".to_string()),
1552
+ enable_ocr: false,
1553
+ force_ocr: false,
1554
+ r#async: true,
1555
+ };
1556
+
1557
+ let result = server.extract_bytes(Parameters(params)).await;
1558
+
1559
+ assert!(result.is_ok() || result.is_err());
1560
+ }
1561
+
1562
+ #[tokio::test]
1563
+ async fn test_extract_bytes_with_valid_pdf_bytes() {
1564
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1565
+
1566
+ let pdf_path = get_test_path("pdfs_with_tables/tiny.pdf");
1567
+
1568
+ if std::path::Path::new(&pdf_path).exists() {
1569
+ let pdf_bytes = std::fs::read(&pdf_path).unwrap();
1570
+ let encoded = BASE64_STANDARD.encode(&pdf_bytes);
1571
+
1572
+ let params = ExtractBytesParams {
1573
+ data: encoded,
1574
+ mime_type: Some("application/pdf".to_string()),
1575
+ enable_ocr: false,
1576
+ force_ocr: false,
1577
+ r#async: true,
1578
+ };
1579
+
1580
+ let result = server.extract_bytes(Parameters(params)).await;
1581
+
1582
+ assert!(result.is_ok(), "PDF bytes extraction should succeed");
1583
+ let call_result = result.unwrap();
1584
+ assert!(!call_result.content.is_empty());
1585
+ }
1586
+ }
1587
+
1588
+ #[tokio::test]
1589
+ async fn test_extract_bytes_mime_type_auto_detection() {
1590
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1591
+
1592
+ let text_content = b"Plain text content for testing";
1593
+ let encoded = BASE64_STANDARD.encode(text_content);
1594
+
1595
+ let params = ExtractBytesParams {
1596
+ data: encoded,
1597
+ mime_type: None,
1598
+ enable_ocr: false,
1599
+ force_ocr: false,
1600
+ r#async: true,
1601
+ };
1602
+
1603
+ let result = server.extract_bytes(Parameters(params)).await;
1604
+
1605
+ assert!(result.is_ok() || result.is_err());
1606
+ }
1607
+
1608
+ #[tokio::test]
1609
+ async fn test_batch_extract_preserves_file_order() {
1610
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1611
+
1612
+ let file1 = get_test_path("pdfs_with_tables/tiny.pdf");
1613
+ let file2 = get_test_path("pdfs_with_tables/medium.pdf");
1614
+
1615
+ if std::path::Path::new(&file1).exists() && std::path::Path::new(&file2).exists() {
1616
+ let params = BatchExtractFilesParams {
1617
+ paths: vec![file1.to_string(), file2.to_string()],
1618
+ enable_ocr: false,
1619
+ force_ocr: false,
1620
+ r#async: true,
1621
+ };
1622
+
1623
+ let result = server.batch_extract_files(Parameters(params)).await;
1624
+
1625
+ if result.is_ok() {
1626
+ let call_result = result.unwrap();
1627
+ if let Some(content) = call_result.content.first()
1628
+ && let RawContent::Text(text) = &content.raw
1629
+ {
1630
+ assert!(text.text.contains("Document 1"));
1631
+ assert!(text.text.contains("Document 2"));
1632
+
1633
+ let doc1_pos = text.text.find("Document 1");
1634
+ let doc2_pos = text.text.find("Document 2");
1635
+ if let (Some(pos1), Some(pos2)) = (doc1_pos, doc2_pos) {
1636
+ assert!(pos1 < pos2, "Documents should be in order");
1637
+ }
1638
+ }
1639
+ }
1640
+ }
1641
+ }
1642
+
1643
+ #[tokio::test]
1644
+ async fn test_cache_clear_is_idempotent() {
1645
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1646
+
1647
+ let result1 = server.cache_clear(Parameters(()));
1648
+ assert!(result1.is_ok());
1649
+
1650
+ let result2 = server.cache_clear(Parameters(()));
1651
+ assert!(result2.is_ok());
1652
+ }
1653
+
1654
+ #[tokio::test]
1655
+ async fn test_cache_clear_returns_metrics() {
1656
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1657
+
1658
+ let result = server.cache_clear(Parameters(()));
1659
+
1660
+ assert!(result.is_ok());
1661
+ let call_result = result.unwrap();
1662
+ if let Some(content) = call_result.content.first()
1663
+ && let RawContent::Text(text) = &content.raw
1664
+ {
1665
+ assert!(text.text.contains("Removed files:"));
1666
+ assert!(text.text.contains("Freed space:"));
1667
+ }
1668
+ }
1669
+
1670
+ #[test]
1671
+ fn test_error_mapping_preserves_error_context() {
1672
+ let validation_error = KreuzbergError::validation("invalid file path");
1673
+ let mcp_error = map_kreuzberg_error_to_mcp(validation_error);
1674
+
1675
+ assert!(mcp_error.message.contains("invalid file path"));
1676
+ }
1677
+
1678
+ #[test]
1679
+ fn test_io_errors_bubble_up_as_internal() {
1680
+ // OSError/RuntimeError must bubble up - system errors need user reports ~keep
1681
+ let io_error = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "access denied");
1682
+ let kreuzberg_error = KreuzbergError::Io(io_error);
1683
+ let mcp_error = map_kreuzberg_error_to_mcp(kreuzberg_error);
1684
+
1685
+ assert_eq!(mcp_error.code.0, -32603);
1686
+ assert!(mcp_error.message.contains("System I/O error"));
1687
+ }
1688
+
1689
+ #[test]
1690
+ fn test_all_error_variants_have_mappings() {
1691
+ let errors = vec![
1692
+ KreuzbergError::validation("test"),
1693
+ KreuzbergError::UnsupportedFormat("test/unknown".to_string()),
1694
+ KreuzbergError::MissingDependency("test-dep".to_string()),
1695
+ KreuzbergError::parsing("test"),
1696
+ KreuzbergError::Io(std::io::Error::other("test")),
1697
+ KreuzbergError::ocr("test"),
1698
+ KreuzbergError::cache("test"),
1699
+ KreuzbergError::image_processing("test"),
1700
+ KreuzbergError::serialization("test"),
1701
+ KreuzbergError::Plugin {
1702
+ message: "test".to_string(),
1703
+ plugin_name: "test-plugin".to_string(),
1704
+ },
1705
+ KreuzbergError::LockPoisoned("test".to_string()),
1706
+ KreuzbergError::Other("test".to_string()),
1707
+ ];
1708
+
1709
+ for error in errors {
1710
+ let mcp_error = map_kreuzberg_error_to_mcp(error);
1711
+
1712
+ assert!(mcp_error.code.0 < 0, "Error code should be negative");
1713
+
1714
+ assert!(!mcp_error.message.is_empty());
1715
+ }
1716
+ }
1717
+
1718
+ #[tokio::test]
1719
+ async fn test_response_includes_metadata() {
1720
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1721
+
1722
+ let test_file = get_test_path("pdfs_with_tables/tiny.pdf");
1723
+
1724
+ if std::path::Path::new(&test_file).exists() {
1725
+ let params = ExtractFileParams {
1726
+ path: test_file.to_string(),
1727
+ mime_type: None,
1728
+ enable_ocr: false,
1729
+ force_ocr: false,
1730
+ r#async: true,
1731
+ };
1732
+
1733
+ let result = server.extract_file(Parameters(params)).await;
1734
+
1735
+ assert!(result.is_ok());
1736
+ let call_result = result.unwrap();
1737
+
1738
+ if let Some(content) = call_result.content.first()
1739
+ && let RawContent::Text(text) = &content.raw
1740
+ {
1741
+ assert!(text.text.contains("Metadata:"));
1742
+ }
1743
+ }
1744
+ }
1745
+
1746
+ #[tokio::test]
1747
+ async fn test_response_includes_content_length() {
1748
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1749
+
1750
+ let test_file = get_test_path("pdfs_with_tables/tiny.pdf");
1751
+
1752
+ if std::path::Path::new(&test_file).exists() {
1753
+ let params = ExtractFileParams {
1754
+ path: test_file.to_string(),
1755
+ mime_type: None,
1756
+ enable_ocr: false,
1757
+ force_ocr: false,
1758
+ r#async: true,
1759
+ };
1760
+
1761
+ let result = server.extract_file(Parameters(params)).await;
1762
+
1763
+ assert!(result.is_ok());
1764
+ let call_result = result.unwrap();
1765
+
1766
+ if let Some(content) = call_result.content.first()
1767
+ && let RawContent::Text(text) = &content.raw
1768
+ {
1769
+ assert!(text.text.contains("characters"));
1770
+ assert!(text.text.contains("Content"));
1771
+ }
1772
+ }
1773
+ }
1774
+
1775
+ #[tokio::test]
1776
+ async fn test_server_is_thread_safe() {
1777
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1778
+
1779
+ let server1 = server.clone();
1780
+ let server2 = server.clone();
1781
+
1782
+ let handle1 = tokio::spawn(async move { server1.get_info() });
1783
+
1784
+ let handle2 = tokio::spawn(async move { server2.get_info() });
1785
+
1786
+ let info1 = handle1.await.unwrap();
1787
+ let info2 = handle2.await.unwrap();
1788
+
1789
+ assert_eq!(info1.server_info.name, info2.server_info.name);
1790
+ }
1791
+
1792
+ #[test]
1793
+ fn test_extract_file_params_serialization() {
1794
+ let params = ExtractFileParams {
1795
+ path: "/test.pdf".to_string(),
1796
+ mime_type: Some("application/pdf".to_string()),
1797
+ enable_ocr: true,
1798
+ force_ocr: false,
1799
+ r#async: true,
1800
+ };
1801
+
1802
+ let json = serde_json::to_string(&params).unwrap();
1803
+ let deserialized: ExtractFileParams = serde_json::from_str(&json).unwrap();
1804
+
1805
+ assert_eq!(params.path, deserialized.path);
1806
+ assert_eq!(params.mime_type, deserialized.mime_type);
1807
+ assert_eq!(params.enable_ocr, deserialized.enable_ocr);
1808
+ assert_eq!(params.force_ocr, deserialized.force_ocr);
1809
+ assert_eq!(params.r#async, deserialized.r#async);
1810
+ }
1811
+
1812
+ #[test]
1813
+ fn test_extract_bytes_params_serialization() {
1814
+ let params = ExtractBytesParams {
1815
+ data: "SGVsbG8=".to_string(),
1816
+ mime_type: None,
1817
+ enable_ocr: false,
1818
+ force_ocr: false,
1819
+ r#async: false,
1820
+ };
1821
+
1822
+ let json = serde_json::to_string(&params).unwrap();
1823
+ let deserialized: ExtractBytesParams = serde_json::from_str(&json).unwrap();
1824
+
1825
+ assert_eq!(params.data, deserialized.data);
1826
+ }
1827
+
1828
+ #[test]
1829
+ fn test_batch_extract_params_serialization() {
1830
+ let params = BatchExtractFilesParams {
1831
+ paths: vec!["/a.pdf".to_string(), "/b.pdf".to_string()],
1832
+ enable_ocr: true,
1833
+ force_ocr: true,
1834
+ r#async: true,
1835
+ };
1836
+
1837
+ let json = serde_json::to_string(&params).unwrap();
1838
+ let deserialized: BatchExtractFilesParams = serde_json::from_str(&json).unwrap();
1839
+
1840
+ assert_eq!(params.paths, deserialized.paths);
1841
+ assert_eq!(params.enable_ocr, deserialized.enable_ocr);
1842
+ }
1843
+
1844
+ #[test]
1845
+ fn test_detect_mime_type_params_serialization() {
1846
+ let params = DetectMimeTypeParams {
1847
+ path: "/test.pdf".to_string(),
1848
+ use_content: false,
1849
+ };
1850
+
1851
+ let json = serde_json::to_string(&params).unwrap();
1852
+ let deserialized: DetectMimeTypeParams = serde_json::from_str(&json).unwrap();
1853
+
1854
+ assert_eq!(params.path, deserialized.path);
1855
+ assert_eq!(params.use_content, deserialized.use_content);
1856
+ }
1857
+
1858
+ #[tokio::test]
1859
+ async fn test_extract_file_respects_custom_default_config() {
1860
+ let custom_config = ExtractionConfig {
1861
+ use_cache: false,
1862
+ ..Default::default()
1863
+ };
1864
+
1865
+ let server = KreuzbergMcp::with_config(custom_config);
1866
+
1867
+ let test_file = get_test_path("pdfs_with_tables/tiny.pdf");
1868
+
1869
+ if std::path::Path::new(&test_file).exists() {
1870
+ let params = ExtractFileParams {
1871
+ path: test_file.to_string(),
1872
+ mime_type: None,
1873
+ enable_ocr: false,
1874
+ force_ocr: false,
1875
+ r#async: true,
1876
+ };
1877
+
1878
+ let result = server.extract_file(Parameters(params)).await;
1879
+
1880
+ assert!(result.is_ok() || result.is_err());
1881
+ }
1882
+ }
1883
+
1884
+ #[tokio::test]
1885
+ async fn test_batch_extract_with_single_file() {
1886
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1887
+
1888
+ let test_file = get_test_path("pdfs_with_tables/tiny.pdf");
1889
+
1890
+ if std::path::Path::new(&test_file).exists() {
1891
+ let params = BatchExtractFilesParams {
1892
+ paths: vec![test_file.to_string()],
1893
+ enable_ocr: false,
1894
+ force_ocr: false,
1895
+ r#async: true,
1896
+ };
1897
+
1898
+ let result = server.batch_extract_files(Parameters(params)).await;
1899
+
1900
+ assert!(result.is_ok());
1901
+ let call_result = result.unwrap();
1902
+ assert!(!call_result.content.is_empty());
1903
+ }
1904
+ }
1905
+
1906
+ #[tokio::test]
1907
+ async fn test_detect_mime_type_with_extension_only() {
1908
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1909
+
1910
+ let test_file = get_test_path("pdfs_with_tables/tiny.pdf");
1911
+
1912
+ if std::path::Path::new(&test_file).exists() {
1913
+ let params = DetectMimeTypeParams {
1914
+ path: test_file.to_string(),
1915
+ use_content: false,
1916
+ };
1917
+
1918
+ let result = server.detect_mime_type(Parameters(params));
1919
+
1920
+ assert!(result.is_ok());
1921
+ let call_result = result.unwrap();
1922
+ if let Some(content) = call_result.content.first()
1923
+ && let RawContent::Text(text) = &content.raw
1924
+ {
1925
+ assert!(text.text.contains("pdf") || text.text.contains("PDF"));
1926
+ }
1927
+ }
1928
+ }
1929
+
1930
+ #[tokio::test]
1931
+ async fn test_detect_mime_type_with_content_analysis() {
1932
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1933
+
1934
+ let test_file = get_test_path("pdfs_with_tables/tiny.pdf");
1935
+
1936
+ if std::path::Path::new(&test_file).exists() {
1937
+ let params = DetectMimeTypeParams {
1938
+ path: test_file.to_string(),
1939
+ use_content: true,
1940
+ };
1941
+
1942
+ let result = server.detect_mime_type(Parameters(params));
1943
+
1944
+ assert!(result.is_ok());
1945
+ }
1946
+ }
1947
+
1948
+ #[tokio::test]
1949
+ async fn test_cache_stats_returns_valid_data() {
1950
+ let server = KreuzbergMcp::with_config(ExtractionConfig::default());
1951
+
1952
+ let result = server.cache_stats(Parameters(()));
1953
+
1954
+ assert!(result.is_ok());
1955
+ let call_result = result.unwrap();
1956
+ if let Some(content) = call_result.content.first()
1957
+ && let RawContent::Text(text) = &content.raw
1958
+ {
1959
+ assert!(text.text.contains("Cache Statistics"));
1960
+ assert!(text.text.contains("Directory:"));
1961
+ assert!(text.text.contains("Total files:"));
1962
+ assert!(text.text.contains("Total size:"));
1963
+ assert!(text.text.contains("Available space:"));
1964
+ assert!(text.text.contains("Oldest file age:"));
1965
+ assert!(text.text.contains("Newest file age:"));
1966
+ }
1967
+ }
1968
+ }