Repository navigation
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds HTML sanitization for MinerU parser sections (normalize tags, unescape entities, collapse whitespace) and skips empty sanitized blocks; hardens MCP server endpoints with URL safety validation and DNS pinning during tool discovery/execution, and updates tests to stub safety/pinning helpers. ChangesText Sanitization for MinerU Parser
MCP DNS/URL safety and tests
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
deepdoc/parser/mineru_parser.py (1)
642-664:⚠️ Potential issue | 🟠 Major | ⚡ Quick winSanitizing all content types can corrupt code/equation text
On Line 662,
_sanitize_section_textruns for every type. ForMinerUContentType.CODE/MinerUContentType.EQUATION, valid content like generics or inequalities (<T>,a < b) can be stripped by Line 221 regex.Proposed fix
- section = self._sanitize_section_text(section) + if output["type"] in {MinerUContentType.TEXT, MinerUContentType.TABLE, MinerUContentType.IMAGE, MinerUContentType.LIST}: + section = self._sanitize_section_text(section) if not section: continue🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@deepdoc/parser/mineru_parser.py` around lines 642 - 664, The sanitizer _sanitize_section_text is being applied to every block, which corrupts CODE and EQUATION content (MinerUContentType.CODE and MinerUContentType.EQUATION) because its regex (used around Line 221) removes or alters angle-bracket/inequality constructs; update the parsing flow in MinerU parser so that for outputs with type CODE or EQUATION you either skip _sanitize_section_text entirely or pass the section through a safe sanitizer variant that preserves <, > and common code tokens (adjust logic around where section is set and where _sanitize_section_text is called), leaving sanitization unchanged for other types like TEXT, TABLE, LIST, IMAGE, and DISCARDED.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@deepdoc/parser/mineru_parser.py`:
- Around line 221-223: The code removes HTML tags from the variable section
using re.sub(r"(?is)<[^>]+>", "", section) before calling
html.unescape(section), which misses encoded tags like <td>; fix by
calling html.unescape on section first and then run the tag-stripping regex
(i.e., swap the order of html.unescape(...) and the re.sub(...) call around the
section variable in the parser function in mineru_parser.py so encoded entities
are decoded prior to regex removal).
- Around line 662-664: The loop that calls self._sanitize_section_text(section)
and then silently continues when the result is empty should emit a debug log so
dropped sections are observable; update the block after calling
_sanitize_section_text in the method containing that loop to call the parser's
logger (e.g., self.logger.debug) with a short message indicating the section was
dropped after sanitization and include identifying context such as the original
(pre-sanitized) snippet or an index and the fact that _sanitize_section_text
returned empty. Ensure the log is at debug level and does not raise exceptions
if the logger is missing.
---
Outside diff comments:
In `@deepdoc/parser/mineru_parser.py`:
- Around line 642-664: The sanitizer _sanitize_section_text is being applied to
every block, which corrupts CODE and EQUATION content (MinerUContentType.CODE
and MinerUContentType.EQUATION) because its regex (used around Line 221) removes
or alters angle-bracket/inequality constructs; update the parsing flow in MinerU
parser so that for outputs with type CODE or EQUATION you either skip
_sanitize_section_text entirely or pass the section through a safe sanitizer
variant that preserves <, > and common code tokens (adjust logic around where
section is set and where _sanitize_section_text is called), leaving sanitization
unchanged for other types like TEXT, TABLE, LIST, IMAGE, and DISCARDED.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: e7c3e104-df51-4447-9631-52d51534a49f
📒 Files selected for processing (1)
deepdoc/parser/mineru_parser.py
There was a problem hiding this comment.
🧹 Nitpick comments (1)
api/apps/restful_apis/mcp_api.py (1)
303-314: ⚡ Quick winAdd logging for the new SSRF / authz rejection branches.
The new validation paths (unsafe URL on lines 303–306 and missing/foreign MCP server on lines 312–314) silently return an error message to the client. For SSRF-related rejections in particular, an audit/warning log line including the offending URL (or at least the hostname) and tenant id is useful for monitoring and incident response, and the missing-record branch is a useful authz signal as well.
📝 Suggested logging additions
+import logging @@ try: hostname, resolved_ip = assert_url_is_safe(url) except ValueError as exc: + logging.warning("MCP test rejected unsafe URL %r for tenant %s: %s", url, current_user.id, exc) return get_data_error_result(message=str(exc)) @@ mcp_server_record = MCPServerService.get_or_none(id=mcp_id, tenant_id=current_user.id) if mcp_server_record is None: + logging.warning("MCP test: server %s not found for tenant %s", mcp_id, current_user.id) return get_data_error_result(message=f"Cannot find MCP server {mcp_id} for user {current_user.id}")As per coding guidelines: "Add logging for new flows".
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/apps/restful_apis/mcp_api.py` around lines 303 - 314, Add audit/warning logs for the new rejection branches: when assert_url_is_safe(url) raises ValueError, log an audit/warning entry including the offending url (or hostname returned by assert_url_is_safe if available) and current_user.id before returning get_data_error_result; similarly, when MCPServerService.get_or_none(id=mcp_id, tenant_id=current_user.id) returns None, log a warning containing mcp_id and current_user.id to capture the authorization/missing-record event, then return get_data_error_result as before. Use the existing logger (or processLogger) consistent with surrounding code and ensure logs avoid leaking sensitive data beyond hostname/ID.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@api/apps/restful_apis/mcp_api.py`:
- Around line 303-314: Add audit/warning logs for the new rejection branches:
when assert_url_is_safe(url) raises ValueError, log an audit/warning entry
including the offending url (or hostname returned by assert_url_is_safe if
available) and current_user.id before returning get_data_error_result;
similarly, when MCPServerService.get_or_none(id=mcp_id,
tenant_id=current_user.id) returns None, log a warning containing mcp_id and
current_user.id to capture the authorization/missing-record event, then return
get_data_error_result as before. Use the existing logger (or processLogger)
consistent with surrounding code and ensure logs avoid leaking sensitive data
beyond hostname/ID.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 62815701-c550-4898-85b3-b36b03453da7
📒 Files selected for processing (1)
api/apps/restful_apis/mcp_api.py
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14920 +/- ##
==========================================
- Coverage 94.16% 93.12% -1.05%
==========================================
Files 10 10
Lines 703 713 +10
Branches 112 116 +4
==========================================
+ Hits 662 664 +2
- Misses 25 29 +4
- Partials 16 20 +4 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
|
CI failure. |
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
api/apps/restful_apis/mcp_api.py (1)
324-329:⚠️ Potential issue | 🟠 Major | ⚡ Quick winDon't let session-close failures override the real response.
If
close_multiple_mcp_toolcall_sessionsraises inside thefinally, it will mask either the handledTest MCP errorat Line 327 or a successful tool list and turn the request into a 500. Cleanup should be best-effort here.Suggested fix
try: tools = await thread_pool_exec(tool_call_session.get_tools, timeout) except Exception as e: return get_data_error_result(message=f"Test MCP error: {e}") finally: - await thread_pool_exec(close_multiple_mcp_toolcall_sessions, [tool_call_session]) + try: + await thread_pool_exec(close_multiple_mcp_toolcall_sessions, [tool_call_session]) + except Exception: + logger.exception("Failed to close MCP tool-call session", extra={"mcp_id": mcp_id})🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/apps/restful_apis/mcp_api.py` around lines 324 - 329, The finally block currently awaits close_multiple_mcp_toolcall_sessions and any exception there can mask the original result from the try/except (e.g., the get_data_error_result or a successful tools response); change the cleanup to be best-effort by wrapping the await thread_pool_exec(close_multiple_mcp_toolcall_sessions, [tool_call_session]) in its own try/except that catches exceptions and logs them (but does not re-raise), ensuring that exceptions from close_multiple_mcp_toolcall_sessions do not override the return produced by the earlier exception handler or normal flow (references: thread_pool_exec, tool_call_session.get_tools, close_multiple_mcp_toolcall_sessions, get_data_error_result).
🧹 Nitpick comments (2)
test/testcases/restful_api/test_mcp_routes_unit.py (1)
695-698: ⚡ Quick winAdd a case where
assert_url_is_saferaisesValueError.This matrix always stubs the helper to succeed, so the new
except ValueErrorpath intest_mcpis never asserted. A small negative case here would lock in the code-102 behavior that this PR added.Suggested test addition
def test_test_mcp_route_matrix_unit(monkeypatch): module = _load_mcp_api(monkeypatch) monkeypatch.setattr(module, "assert_url_is_safe", lambda _url: ("a", "93.184.216.34")) monkeypatch.setattr(module, "pin_dns_global", lambda *_args, **_kwargs: nullcontext()) + + monkeypatch.setattr( + module, + "assert_url_is_safe", + lambda _url: (_ for _ in ()).throw(ValueError("unsafe MCP url")), + ) + _set_request_json(monkeypatch, module, {"url": "http://a", "server_type": "sse"}) + res = _run(module.test_mcp("mcp-1")) + assert res["code"] == 102 + assert "unsafe MCP url" in res["message"] + + monkeypatch.setattr(module, "assert_url_is_safe", lambda _url: ("a", "93.184.216.34"))🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@test/testcases/restful_api/test_mcp_routes_unit.py` around lines 695 - 698, The current test matrix in test_test_mcp_route_matrix_unit always stubs assert_url_is_safe to succeed, so add an additional case where module.assert_url_is_safe raises ValueError to exercise the new except ValueError path in test_mcp; modify test_test_mcp_route_matrix_unit to include a second monkeypatch or parametrized branch that sets module.assert_url_is_safe = lambda _url: (_ for _ in ()).throw(ValueError("unsafe url")) (or equivalent) and keep pin_dns_global patched as before, then assert the handler returns the code-102 behavior expected by test_mcp.api/apps/restful_apis/mcp_api.py (1)
308-311: ⚡ Quick winAdd server-side logs for the new rejection/error paths.
The new URL-safety rejection branch and the MCP test failure branch return client errors, but neither records what failed on the server side. That will make support/debugging much harder once this ships.
As per coding guidelines, "Add logging for new flows".
Also applies to: 326-327
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/apps/restful_apis/mcp_api.py` around lines 308 - 311, When assert_url_is_safe(url) raises ValueError and when the MCP test-failure branch returns a client error, add server-side logging so failures are recorded: inside the except ValueError as exc block (around assert_url_is_safe) call the module logger (e.g., logger.error or logger.exception) to log the url, the exception message/stack (exc_info=True), and any hostname/resolved_ip if available before returning get_data_error_result; do the same in the MCP test failure branch (the code that returns the client error for the MCP test) to log the failing input, error details, and any diagnostic values so support can trace the failure.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@api/apps/restful_apis/mcp_api.py`:
- Around line 308-311: The URL safety check added around the
/mcp/servers/<mcp_id>/test route must be applied to the other MCP tool-discovery
flows: in the create, update, and import_multiple handlers call
assert_url_is_safe(url) before invoking get_mcp_tools(url) (mirror the
try/except pattern that captures ValueError and returns
get_data_error_result(message=str(exc))); use the returned hostname/resolved_ip
pair to perform DNS-pinning or to pass a pinned IP into downstream requests made
by get_mcp_tools so lookups cannot be spoofed. Ensure each occurrence of
get_mcp_tools in create, update, and import_multiple is guarded the same way and
that failures return the same error result.
---
Outside diff comments:
In `@api/apps/restful_apis/mcp_api.py`:
- Around line 324-329: The finally block currently awaits
close_multiple_mcp_toolcall_sessions and any exception there can mask the
original result from the try/except (e.g., the get_data_error_result or a
successful tools response); change the cleanup to be best-effort by wrapping the
await thread_pool_exec(close_multiple_mcp_toolcall_sessions,
[tool_call_session]) in its own try/except that catches exceptions and logs them
(but does not re-raise), ensuring that exceptions from
close_multiple_mcp_toolcall_sessions do not override the return produced by the
earlier exception handler or normal flow (references: thread_pool_exec,
tool_call_session.get_tools, close_multiple_mcp_toolcall_sessions,
get_data_error_result).
---
Nitpick comments:
In `@api/apps/restful_apis/mcp_api.py`:
- Around line 308-311: When assert_url_is_safe(url) raises ValueError and when
the MCP test-failure branch returns a client error, add server-side logging so
failures are recorded: inside the except ValueError as exc block (around
assert_url_is_safe) call the module logger (e.g., logger.error or
logger.exception) to log the url, the exception message/stack (exc_info=True),
and any hostname/resolved_ip if available before returning
get_data_error_result; do the same in the MCP test failure branch (the code that
returns the client error for the MCP test) to log the failing input, error
details, and any diagnostic values so support can trace the failure.
In `@test/testcases/restful_api/test_mcp_routes_unit.py`:
- Around line 695-698: The current test matrix in
test_test_mcp_route_matrix_unit always stubs assert_url_is_safe to succeed, so
add an additional case where module.assert_url_is_safe raises ValueError to
exercise the new except ValueError path in test_mcp; modify
test_test_mcp_route_matrix_unit to include a second monkeypatch or parametrized
branch that sets module.assert_url_is_safe = lambda _url: (_ for _ in
()).throw(ValueError("unsafe url")) (or equivalent) and keep pin_dns_global
patched as before, then assert the handler returns the code-102 behavior
expected by test_mcp.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 622b9d28-53f3-423a-8e7d-23aae3b11537
📒 Files selected for processing (3)
api/apps/restful_apis/mcp_api.pytest/testcases/restful_api/test_mcp_routes_unit.pytest/testcases/test_web_api/test_mcp_server_app/test_mcp_server_app_unit.py
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@api/apps/restful_apis/mcp_api.py`:
- Around line 125-128: Before calling assert_url_is_safe(url) validate that the
incoming url is a str and return get_data_error_result(...) for non-string
values, then proceed with the existing try/except for ValueError; specifically,
at each call site where you currently do "hostname, resolved_ip =
assert_url_is_safe(url)" first add a guard like "if not isinstance(url, str):
return get_data_error_result(message='URL must be a string')" and then wrap the
call in the existing try/except ValueError block; apply this pattern to all
places in the module that call assert_url_is_safe(url) (the three other sites
mentioned) so AttributeError from non-string inputs cannot escape to a 500.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: ab2e2a7d-99e3-43b0-b0d5-b7fc5b388b15
📒 Files selected for processing (3)
api/apps/restful_apis/mcp_api.pytest/testcases/restful_api/test_mcp_routes_unit.pytest/testcases/test_web_api/test_mcp_server_app/test_mcp_server_app_unit.py
|
@JinHai-CN Could you plz review my PR? |
1dd5cdc to
d2559a9
Compare
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
test/unit_test/deepdoc/parser/test_mineru_parser.py (1)
40-69:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winAdd required pytest priority markers to new tests.
These tests are missing repo-required
p1/p2/p3markers.Proposed fix
import importlib.util import logging import sys from pathlib import Path from types import ModuleType +import pytest @@ +@pytest.mark.p2 def test_sanitize_section_text_removes_escaped_html_tags(monkeypatch): @@ +@pytest.mark.p2 def test_transfer_to_sections_logs_sections_dropped_after_sanitization(monkeypatch, caplog):As per coding guidelines,
test/**/*.py: Use pytest with priority markers (p1/p2/p3) for Python backend tests.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@test/unit_test/deepdoc/parser/test_mineru_parser.py` around lines 40 - 69, Add the required pytest priority markers to the two new tests by decorating them (e.g., `@pytest.mark.p1` or `@pytest.mark.p2` as appropriate) and ensure pytest is imported; specifically, add the marker decorator above test_sanitize_section_text_removes_escaped_html_tags and test_transfer_to_sections_logs_sections_dropped_after_sanitization in test_mineru_parser.py, keeping the existing function names (MinerUParser, _sanitize_section_text, _transfer_to_sections) intact so CI recognizes their priority tags.api/apps/restful_apis/mcp_api.py (1)
254-257:⚠️ Potential issue | 🟠 Major | ⚡ Quick winHandle non-dict server configs before key membership checks.
Line 255 assumes
configis iterable/mapping. If onemcpServersvalue is a scalar (e.g.,1), it raisesTypeError, hits the outerexcept, and aborts the whole batch import instead of returning per-server failure results.🔧 Suggested fix
for server_name, config in servers.items(): + if not isinstance(config, dict): + results.append({"server": server_name, "success": False, "message": "Invalid server config."}) + continue if not all(key in config for key in {"type", "url"}): results.append({"server": server_name, "success": False, "message": "Missing required fields (type or url)"}) continueAlso applies to: 262-268
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/apps/restful_apis/mcp_api.py` around lines 254 - 257, The loop over servers (for server_name, config in servers.items()) assumes each config is a mapping; if a config is a scalar it raises TypeError and aborts the batch—fix by first checking isinstance(config, dict) (or collections.abc.Mapping) before testing membership or accessing keys, and if not a dict append a per-server failure to results (using the same structure {"server": server_name, "success": False, "message": "..."}), then continue; apply the same defensive check in the subsequent block that currently accesses config keys around the 262-268 logic so non-dict values produce per-server errors instead of raising.
🧹 Nitpick comments (1)
api/apps/restful_apis/mcp_api.py (1)
59-66: ⚡ Quick winAdd warning logs for URL rejection paths in the new helper.
This helper introduces new security rejection flows but currently returns errors silently; add warning logs for invalid type/empty input and blocked unsafe URLs.
As per coding guidelines `**/*.py`: Add logging for new flows.📝 Suggested patch
+import logging from quart import Response, request @@ from common.ssrf_guard import assert_url_is_safe, pin_dns_global +logger = logging.getLogger(__name__) + @@ def _assert_mcp_url_is_safe(url, invalid_message: str = "Invalid url.") -> tuple[str, str, str | None]: if not isinstance(url, str) or not url: + logger.warning("Rejected MCP URL: invalid type/empty input (type=%s)", type(url).__name__) return "", "", invalid_message try: hostname, resolved_ip = assert_url_is_safe(url) except ValueError as exc: + logger.warning("Rejected MCP URL %r: %s", url, exc) return "", "", str(exc) return hostname, resolved_ip, None🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/apps/restful_apis/mcp_api.py` around lines 59 - 66, In _assert_mcp_url_is_safe, add warning logs for both rejection paths: log a warning when the input is not a non-empty string (include the provided url value/type) and log a warning when assert_url_is_safe raises ValueError (include the exception message and the original url); use the module logger (e.g., the existing logger or create one via logging.getLogger(__name__)) and keep the function return values the same while emitting these warnings to satisfy the Python logging guideline.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@api/apps/restful_apis/mcp_api.py`:
- Around line 254-257: The loop over servers (for server_name, config in
servers.items()) assumes each config is a mapping; if a config is a scalar it
raises TypeError and aborts the batch—fix by first checking isinstance(config,
dict) (or collections.abc.Mapping) before testing membership or accessing keys,
and if not a dict append a per-server failure to results (using the same
structure {"server": server_name, "success": False, "message": "..."}), then
continue; apply the same defensive check in the subsequent block that currently
accesses config keys around the 262-268 logic so non-dict values produce
per-server errors instead of raising.
In `@test/unit_test/deepdoc/parser/test_mineru_parser.py`:
- Around line 40-69: Add the required pytest priority markers to the two new
tests by decorating them (e.g., `@pytest.mark.p1` or `@pytest.mark.p2` as
appropriate) and ensure pytest is imported; specifically, add the marker
decorator above test_sanitize_section_text_removes_escaped_html_tags and
test_transfer_to_sections_logs_sections_dropped_after_sanitization in
test_mineru_parser.py, keeping the existing function names (MinerUParser,
_sanitize_section_text, _transfer_to_sections) intact so CI recognizes their
priority tags.
---
Nitpick comments:
In `@api/apps/restful_apis/mcp_api.py`:
- Around line 59-66: In _assert_mcp_url_is_safe, add warning logs for both
rejection paths: log a warning when the input is not a non-empty string (include
the provided url value/type) and log a warning when assert_url_is_safe raises
ValueError (include the exception message and the original url); use the module
logger (e.g., the existing logger or create one via logging.getLogger(__name__))
and keep the function return values the same while emitting these warnings to
satisfy the Python logging guideline.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: f5ca5a37-d539-4874-8fb4-81c006c14d08
📒 Files selected for processing (5)
api/apps/restful_apis/mcp_api.pydeepdoc/parser/mineru_parser.pytest/testcases/restful_api/test_mcp_routes_unit.pytest/testcases/test_web_api/test_mcp_server_app/test_mcp_server_app_unit.pytest/unit_test/deepdoc/parser/test_mineru_parser.py
Summary
This change fixes ingestion quality issues where MinerU parser output may contain HTML fragments (for example, table-related tags like
<tr>,<td>,<br>), which were previously passed directly into chunking/tokenization and degraded chunk quality.The fix adds a sanitization step in the MinerU parser path so parsed sections are normalized to clean text before chunking.
Change Type (select all)
Related Issue
Root Cause
MinerU output blocks (
text,table_body, captions/footnotes, etc.) could include HTML-style markup.Those strings were transferred into section content and then merged/tokenized without tag cleanup, so chunk text contained parser markup.
Real Behavior Proof
Before fix
After fix
Technical Evidence
deepdoc/parser/mineru_parser.py(_sanitize_section_text)_transfer_to_sectionsappliessection = self._sanitize_section_text(section)Validation Performed
python3 -m py_compile deepdoc/parser/mineru_parser.pyRuntime Validation Note
A direct runtime sample execution was attempted, but this environment is missing dependency
beartype, which blocked import-time execution of parser modules. This does not affect the source-level integration or syntax validity of the patch.Checklist