Skip to content

fix: The output of the parser in the ingestion pipeline contains HTML tags - #14920

Merged
JinHai-CN merged 4 commits into
infiniflow:mainfrom
jonathanchang31:fix/output-ingestion-pipeline-contains
May 25, 2026
Merged

JinHai-CN merged 4 commits into
infiniflow:mainfrom
jonathanchang31:fix/output-ingestion-pipeline-contains

Conversation

@jonathanchang31

@jonathanchang31 jonathanchang31 commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

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)

  • Bug fix
  • Ingestion pipeline improvement
  • Parser/chunking quality fix

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

  • MinerU-derived section content could include literal HTML tags.
  • Chunker consumed those tags as normal text.
  • Result: chunk boundaries and semantic quality were negatively affected.

After fix

  • MinerU section text is sanitized before chunking.
  • HTML tags are removed from section content.
  • Chunking/tokenization now receives cleaner text, improving chunk quality and retrieval consistency.

Technical Evidence

  • Sanitizer definition:
    • deepdoc/parser/mineru_parser.py (_sanitize_section_text)
  • Sanitizer usage in transfer path:
    • _transfer_to_sections applies section = self._sanitize_section_text(section)
  • Transfer path feeds parser output to downstream chunking as before, now with cleaned text.

Validation Performed

  • Source-level verification that sanitizer is wired into MinerU transfer path
  • Syntax check passed:
    • python3 -m py_compile deepdoc/parser/mineru_parser.py
  • End-to-end ingestion test with real MinerU output in this environment
  • Automated unit test added for sanitizer edge-cases

Runtime 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

  • Confirmed issue path in MinerU -> sections -> chunking flow
  • Added targeted sanitization in MinerU parser
  • Ensured sanitization executes before chunking
  • Verified file compiles cleanly
  • Add regression/unit tests for sanitizer cases
  • Run full ingestion smoke test in a dependency-complete environment

@dosubot dosubot Bot added the size:S This PR changes 10-29 lines, ignoring generated files. label May 14, 2026
@coderabbitai

coderabbitai Bot commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds 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.

Changes

Text Sanitization for MinerU Parser

Layer / File(s) Summary
HTML text sanitization helper and integration
deepdoc/parser/mineru_parser.py
Imports html, defines _sanitize_section_text() to normalize MinerU text by converting <br>-like tags and certain closing tags to newlines, stripping other HTML, unescaping entities, collapsing whitespace, and trimming. The sanitizer is applied in _transfer_to_sections() and skips sections that become empty after sanitization.
Unit tests for sanitization and dropping
test/unit_test/deepdoc/parser/test_mineru_parser.py
Adds tests that load the mineru parser in isolation, assert _sanitize_section_text removes escaped HTML tags, and verify _transfer_to_sections drops sanitized-empty sections while logging the drop and content type.

MCP DNS/URL safety and tests

Layer / File(s) Summary
Imports and URL validation
api/apps/restful_apis/mcp_api.py
Adds assert_url_is_safe and pin_dns_global imports and _assert_mcp_url_is_safe helper. Validates url inputs in create, update, import, and test endpoints, converting ValueError into client-facing data errors or per-server import failures.
DNS pinning and tool discovery/execution
api/apps/restful_apis/mcp_api.py
Runs get_mcp_tools and MCP tool execution under pin_dns_global(hostname, resolved_ip), wraps tool retrieval in try/except to return formatted test errors, and ensures MCP tool-call sessions are closed in finally.
Tests: stubbing URL safety and DNS pinning
test/testcases/restful_api/test_mcp_routes_unit.py, test/testcases/test_web_api/test_mcp_server_app/test_mcp_server_app_unit.py
Adds _stub_url_safety helpers and nullcontext usage to monkeypatch assert_url_is_safe and pin_dns_global, introduces unsafe-URL test cases asserting blocked unsafe url, and updates import-multiple payloads and assertions for mixed-result scenarios.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Suggested reviewers

  • JinHai-CN

Poem

I’m a rabbit tidying MinerU hay,
Turning stray
s into neat new day.
Entities unwrapped, blanks made small,
DNS pinned tight when MCP hears the call.
Hoppity-hop — clean text and safe calls all! 🐇✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 3.23% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main fix: removing HTML tags from parser output in the ingestion pipeline, which directly matches the core changes in mineru_parser.py.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description check ✅ Passed The PR description comprehensively covers the problem, change type, root cause, technical details, and validation performed, aligning well with the template requirements.

✏️ 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 win

Sanitizing all content types can corrupt code/equation text

On Line 662, _sanitize_section_text runs for every type. For MinerUContentType.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 &lt;td&gt;; 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

📥 Commits

Reviewing files that changed from the base of the PR and between bd99a22 and dd8ab33.

📒 Files selected for processing (1)
  • deepdoc/parser/mineru_parser.py

Comment thread deepdoc/parser/mineru_parser.py Resolved
Comment thread deepdoc/parser/mineru_parser.py Resolved
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:S This PR changes 10-29 lines, ignoring generated files. labels May 14, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
api/apps/restful_apis/mcp_api.py (1)

303-314: ⚡ Quick win

Add 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

📥 Commits

Reviewing files that changed from the base of the PR and between dd8ab33 and dbbbfa3.

📒 Files selected for processing (1)
  • api/apps/restful_apis/mcp_api.py

@KevinHuSh KevinHuSh added the ci Continue Integration label May 18, 2026
@KevinHuSh
KevinHuSh marked this pull request as draft May 18, 2026 06:30
@KevinHuSh
KevinHuSh marked this pull request as ready for review May 18, 2026 06:30
@codecov

codecov Bot commented May 18, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.12%. Comparing base (714f777) to head (d2559a9).
⚠️ Report is 147 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@KevinHuSh

Copy link
Copy Markdown
Contributor

CI failure.

=================================== FAILURES ===================================
_______________________ test_test_mcp_route_matrix_unit ________________________
test/testcases/restful_api/test_mcp_routes_unit.py:703: in test_test_mcp_route_matrix_unit
    assert "Unsupported MCP server type" in res["message"]
E   assert 'Unsupported MCP server type' in "Could not resolve hostname 'a': [Errno -2] Name or service not known"

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 win

Don't let session-close failures override the real response.

If close_multiple_mcp_toolcall_sessions raises inside the finally, it will mask either the handled Test MCP error at 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 win

Add a case where assert_url_is_safe raises ValueError.

This matrix always stubs the helper to succeed, so the new except ValueError path in test_mcp is 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 win

Add 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

📥 Commits

Reviewing files that changed from the base of the PR and between dbbbfa3 and d35760f.

📒 Files selected for processing (3)
  • api/apps/restful_apis/mcp_api.py
  • test/testcases/restful_api/test_mcp_routes_unit.py
  • test/testcases/test_web_api/test_mcp_server_app/test_mcp_server_app_unit.py

Comment thread api/apps/restful_apis/mcp_api.py Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between d35760f and 1dd5cdc.

📒 Files selected for processing (3)
  • api/apps/restful_apis/mcp_api.py
  • test/testcases/restful_api/test_mcp_routes_unit.py
  • test/testcases/test_web_api/test_mcp_server_app/test_mcp_server_app_unit.py

Comment thread api/apps/restful_apis/mcp_api.py Resolved
@jonathanchang31

Copy link
Copy Markdown
Contributor Author

@JinHai-CN Could you plz review my PR?

@jonathanchang31
jonathanchang31 force-pushed the fix/output-ingestion-pipeline-contains branch from 1dd5cdc to d2559a9 Compare May 25, 2026 06:04

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 win

Add required pytest priority markers to new tests.

These tests are missing repo-required p1/p2/p3 markers.

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 win

Handle non-dict server configs before key membership checks.

Line 255 assumes config is iterable/mapping. If one mcpServers value is a scalar (e.g., 1), it raises TypeError, hits the outer except, 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)"})
                 continue

Also 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 win

Add 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.

📝 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
As per coding guidelines `**/*.py`: 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 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

📥 Commits

Reviewing files that changed from the base of the PR and between 1dd5cdc and d2559a9.

📒 Files selected for processing (5)
  • api/apps/restful_apis/mcp_api.py
  • deepdoc/parser/mineru_parser.py
  • test/testcases/restful_api/test_mcp_routes_unit.py
  • test/testcases/test_web_api/test_mcp_server_app/test_mcp_server_app_unit.py
  • test/unit_test/deepdoc/parser/test_mineru_parser.py

@JinHai-CN
JinHai-CN merged commit 9d1006e into infiniflow:main May 25, 2026
1 check passed
wangq8 added a commit that referenced this pull request Jun 17, 2026
Follow on issue: #14831 and PR: #14920 to fix the table options, with
table recognition enabled, do not sanitize html tags.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants