kreuzberg 4.0.0.rc2 → 4.0.1

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