Skip to content

fix(agent): enable MCP file preview via doc_id - #15399

Merged
yuzhichang merged 4 commits into
infiniflow:mainfrom
monsterdavidliu-ux:fix/15398-mcp-doc-preview
Jul 3, 2026
Merged

yuzhichang merged 4 commits into
infiniflow:mainfrom
monsterdavidliu-ux:fix/15398-mcp-doc-preview

Conversation

@monsterdavidliu-ux

@monsterdavidliu-ux monsterdavidliu-ux commented May 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

MCP-wrapped agents could only force-download files looked up by doc_id. This adds an explicit preview path and inline response headers for previewable file types.

  • New GET /api/v1/agents/attachments/{attachment_id}/preview — inline preview for PDFs, images, and other safe types (pass ext and/or mime_type)
  • Improved GET /api/v1/documents/{doc_id}/preview — sets inline disposition using the document filename
  • Improved attachment download routing — resolves mime_type / ext query params (no default markdown), supports disposition=inline
  • DocGenerator output — includes URL-encoded preview_url for MCP clients
  • Legacy /document/download/... aliases — still use download semantics; MCP clients should call /preview explicitly

Fixes #15398

Test plan

  • pytest test/unit_test/api/utils/test_file_response_headers.py (6/6)

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 🐖api The modified files are located under directory 'api/apps/sdk' 💞 feature Feature request, pull request that fullfill a new feature. labels May 29, 2026
@coderabbitai

coderabbitai Bot commented May 29, 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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 884dde08-2354-412c-8239-0ea81e0c13f0

📥 Commits

Reviewing files that changed from the base of the PR and between a621d3a and f5c7e7e.

📒 Files selected for processing (1)
  • test/unit_test/api/apps/restful_apis/test_attachment_download_missing_blob.py

📝 Walkthrough

Walkthrough

Centralizes file-response handling, adds agent attachment preview streaming and preview URLs, updates document preview responses, and extends client/test coverage for the preview flow.

Changes

Preview and download attachment infrastructure

Layer / File(s) Summary
Core file response utilities
api/utils/file_response.py
New module defining MIME mappings, forced-attachment rules, filename sanitization, content-type resolution, preview/download header helpers, and preview URL construction.
Consolidate attachment utilities in web_utils
api/utils/web_utils.py
Moves attachment MIME and force-attachment logic to the shared file-response module.
Agent attachment preview and download endpoints
api/apps/restful_apis/agent_api.py
Adds /agents/attachments/<attachment_id>/preview, introduces request metadata extraction and shared streaming, and refactors download handling to use the new header helpers.
Document preview and generated preview URL
api/apps/restful_apis/document_api.py, agent/component/docs_generator.py
Document preview responses use preview-specific headers, and generated document metadata now includes a preview_url.
Frontend API endpoint helper for preview
web/src/utils/api.ts
Adds a helper for building attachment preview URLs with optional query parameters.
File response utilities unit tests
test/unit_test/api/utils/test_file_response_headers.py, test/unit_test/api/apps/restful_apis/test_attachment_download_missing_blob.py
Adds tests for header application, content-type resolution, preview URL generation, and the response-header stub used by the attachment regression test.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Suggested labels: 🐞 bug

Poem

🐰 I hopped through headers, neat and new,
Preview paths now come right through.
Inline for views, download for keep,
The bytes stay tidy, fast, and deep.
A bunny approves this file-filled chore!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% 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 states the main change: enabling MCP file preview via doc_id.
Description check ✅ Passed The description includes the required Summary section and sufficiently explains the feature, impact, and test plan.
Linked Issues check ✅ Passed The PR adds inline preview support, a preview endpoint, and preserves legacy download behavior, matching #15398.
Out of Scope Changes check ✅ Passed The added utility, API, web helper, and tests all support the preview feature and do not appear unrelated.

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.

@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: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
api/apps/backward_compat.py (1)

605-619: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Keep legacy /download/... aliases on download semantics.

These handlers now return the preview endpoint, which changes a backward-compatibility route from Content-Disposition: attachment to inline behavior. Existing clients calling /document/download/... can start opening files in-browser instead of downloading them, which is a breaking API change unrelated to the new preview route itself. Please keep these aliases wired to the download handler and let MCP clients use /preview explicitly.

Also applies to: 622-636

🤖 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/backward_compat.py` around lines 605 - 619, The deprecated
`/document/download/<doc_id>` route (function deprecated_document_download) must
preserve download semantics instead of delegating to the preview endpoint:
change its implementation to call the agent API's download behavior (the
download-specific handler on agent_api that returns a response with
Content-Disposition: attachment) or, if no such helper exists, wrap the preview
response and set the Content-Disposition header to attachment with the original
filename; do the same fix for the other deprecated download alias noted in the
same area (the second deprecated `/document/download/...` handler around lines
622-636) so both legacy aliases continue forcing a file download while
`/preview` remains for inline preview.
🤖 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/utils/file_response.py`:
- Around line 139-146: The helper agent_attachment_preview_path currently
appends raw ext and mime_type values into the query string, which breaks values
containing reserved characters (e.g., "image/svg+xml"); fix by URL-encoding
these parameters before building the suffix. Update
agent_attachment_preview_path to build a params dict only with non-None values
and use urllib.parse.urlencode(params, safe='') (import urllib.parse) to produce
the query string, then append that encoded string as the suffix when returning
the preview URL.

In `@test/unit_test/api/utils/test_file_response_headers.py`:
- Around line 20-48: Add pytest priority markers to each test function in this
file: decorate test_apply_preview_sets_inline_for_pdf,
test_apply_preview_forces_attachment_for_html,
test_apply_download_sets_attachment_for_pdf,
test_resolve_attachment_content_type_prefers_mime_type, and
test_agent_attachment_preview_path_includes_query with the appropriate
`@pytest.mark.p1` / p2 / p3 marker per guidelines so they are picked up by the
repo test-selection; update imports to include pytest.mark if missing and ensure
the chosen priority matches project policy for backend tests.

In `@web/src/utils/api.ts`:
- Around line 226-227: getAttachmentFilePreview currently builds a preview URL
from just docId which omits required metadata (ext/mime_type) and causes backend
to default to application/octet-stream; update getAttachmentFilePreview to
accept optional parameters ext and mime_type (or a single metadata object) and
include them as query params when constructing the URL, or stop reconstructing
the URL and instead return the preview_url supplied by DocGenerator (prefer the
latter if available); locate the helper named getAttachmentFilePreview in
web/src/utils/api.ts and modify its signature and implementation to pass-through
or append ext and/or mime_type, or wire the DocGenerator preview_url into
callers instead of reconstructing.

---

Outside diff comments:
In `@api/apps/backward_compat.py`:
- Around line 605-619: The deprecated `/document/download/<doc_id>` route
(function deprecated_document_download) must preserve download semantics instead
of delegating to the preview endpoint: change its implementation to call the
agent API's download behavior (the download-specific handler on agent_api that
returns a response with Content-Disposition: attachment) or, if no such helper
exists, wrap the preview response and set the Content-Disposition header to
attachment with the original filename; do the same fix for the other deprecated
download alias noted in the same area (the second deprecated
`/document/download/...` handler around lines 622-636) so both legacy aliases
continue forcing a file download while `/preview` remains for inline preview.
🪄 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: cc404b07-3317-42c5-80ca-68da7d2f3331

📥 Commits

Reviewing files that changed from the base of the PR and between b79f79d and 1b84213.

📒 Files selected for processing (8)
  • agent/component/docs_generator.py
  • api/apps/backward_compat.py
  • api/apps/restful_apis/agent_api.py
  • api/apps/restful_apis/document_api.py
  • api/utils/file_response.py
  • api/utils/web_utils.py
  • test/unit_test/api/utils/test_file_response_headers.py
  • web/src/utils/api.ts

Comment thread api/utils/file_response.py Resolved
Comment thread web/src/utils/api.ts Resolved
@xugangqiang

Copy link
Copy Markdown
Contributor

@monsterdavidliu-ux
Do you think it's a new feature or an existing bug?

@monsterdavidliu-ux

Copy link
Copy Markdown
Contributor Author

I'd classify this as an existing bug, not a new feature.

Why bug: For MCP-wrapped agents, looking up a file by doc_id effectively only exposed download behavior (or wrong Content-Disposition), so inline preview in the client didn't work as users expect from the rest of the document/attachment flows. That's the gap reported in #15398.

What the PR does: Restores the intended behavior — inline preview for previewable types via explicit preview routes/headers and preview_url in DocGenerator output — without changing legacy /document/download/... to inline (those stay attachment/download semantics).

The new /agents/attachments/{id}/preview endpoint is the minimal API surface to fix that bug; I wouldn't treat it as a separate feature request.

Happy to retitle or adjust labels if the team prefers fix vs feat for endpoint additions.

@xugangqiang xugangqiang added the ci Continue Integration label Jun 3, 2026
@xugangqiang
xugangqiang marked this pull request as draft June 3, 2026 04:01
@xugangqiang
xugangqiang marked this pull request as ready for review June 3, 2026 04:01
@codecov

codecov Bot commented Jun 3, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (994b603) to head (f5c7e7e).
⚠️ Report is 16 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15399   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Harness.
📢 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.

@yuzhichang
yuzhichang self-requested a review June 28, 2026 00:49
@yuzhichang

yuzhichang commented Jun 28, 2026 •

Copy link
Copy Markdown
Member

This PR currently has merge conflicts with main and cannot be auto-synced.

Please run locally:

git fetch origin main
git rebase origin/main
# or
git merge origin/main

After resolving the conflicts, push to the current head branch and CI will re-run the review checks.

Triggered by reviewer yuzhichang (request-for-action)

monsterdavidliu-ux and others added 3 commits July 3, 2026 16:53
Add /agents/attachments/{id}/preview with inline Content-Disposition for
previewable types, resolve mime_type/ext on attachment streams, set inline
headers on /documents/{doc_id}/preview, and expose preview_url in DocGenerator
output. Legacy document/download aliases now route to preview.

Fixes infiniflow#15398
URL-encode preview query params, keep legacy download aliases on download
semantics, extend getAttachmentFilePreview with ext/mime metadata, and add
pytest p2 markers plus svg mime encoding coverage.
@yuzhichang
yuzhichang force-pushed the fix/15398-mcp-doc-preview branch from 90173c8 to a621d3a Compare July 3, 2026 10:01

@yuzhichang yuzhichang left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label Jul 3, 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/agent_api.py (1)

2496-2515: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider route-level tests for the new preview/download endpoints.

The referenced test suite (test/unit_test/api/utils/test_file_response_headers.py) covers the header-utility functions but doesn't appear to exercise preview_attachment/download_attachment at the route level (e.g., disposition=inline on the download route, the not-found branch, or ext/mime_type query resolution end-to-end). Given this is the core deliverable of the PR, route-level coverage would give higher confidence.

Want me to draft unit tests for these two routes?

🤖 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/agent_api.py` around lines 2496 - 2515, Add route-level
tests for the new preview_attachment and download_attachment endpoints, since
the current coverage only validates lower-level header helpers. Exercise
preview_attachment and download_attachment end-to-end, including the download
route’s disposition=inline path, the not-found/error branch, and query-driven
ext/mime_type resolution through _stream_agent_attachment. Use the
preview_attachment, download_attachment, and _stream_agent_attachment symbols to
locate the route behavior and verify the response headers and status handling.
🤖 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/agent_api.py`:
- Around line 2496-2515: Add route-level tests for the new preview_attachment
and download_attachment endpoints, since the current coverage only validates
lower-level header helpers. Exercise preview_attachment and download_attachment
end-to-end, including the download route’s disposition=inline path, the
not-found/error branch, and query-driven ext/mime_type resolution through
_stream_agent_attachment. Use the preview_attachment, download_attachment, and
_stream_agent_attachment symbols to locate the route behavior and verify the
response headers and status handling.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 53e57719-3508-4335-8abb-6b2c647e0ee9

📥 Commits

Reviewing files that changed from the base of the PR and between 90173c8 and a621d3a.

📒 Files selected for processing (5)
  • agent/component/docs_generator.py
  • api/apps/restful_apis/agent_api.py
  • api/apps/restful_apis/document_api.py
  • api/utils/file_response.py
  • api/utils/web_utils.py
💤 Files with no reviewable changes (3)
  • api/utils/web_utils.py
  • api/utils/file_response.py
  • api/apps/restful_apis/document_api.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • agent/component/docs_generator.py

@yuzhichang
yuzhichang merged commit 7da4f20 into infiniflow:main Jul 3, 2026
3 checks passed
xugangqiang pushed a commit to xugangqiang/ragflow that referenced this pull request Jul 3, 2026
## Summary
MCP-wrapped agents could only force-download files looked up by
`doc_id`. This adds an explicit preview path and inline response headers
for previewable file types.

- **New** `GET /api/v1/agents/attachments/{attachment_id}/preview` —
inline preview for PDFs, images, and other safe types (pass `ext` and/or
`mime_type`)
- **Improved** `GET /api/v1/documents/{doc_id}/preview` — sets inline
disposition using the document filename
- **Improved** attachment download routing — resolves `mime_type` /
`ext` query params (no default `markdown`), supports
`disposition=inline`
- **DocGenerator output** — includes URL-encoded `preview_url` for MCP
clients
- **Legacy `/document/download/...` aliases** — still use download
semantics; MCP clients should call `/preview` explicitly

Fixes infiniflow#15398

## Test plan
- [x] `pytest test/unit_test/api/utils/test_file_response_headers.py`
(6/6)

---------

Co-authored-by: MkDev11 <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-authored-by: Ling Qin <[email protected]>
yuzhichang pushed a commit that referenced this pull request Jul 6, 2026
xugangqiang pushed a commit to xugangqiang/ragflow that referenced this pull request Jul 6, 2026
## Summary
MCP-wrapped agents could only force-download files looked up by
`doc_id`. This adds an explicit preview path and inline response headers
for previewable file types.

- **New** `GET /api/v1/agents/attachments/{attachment_id}/preview` —
inline preview for PDFs, images, and other safe types (pass `ext` and/or
`mime_type`)
- **Improved** `GET /api/v1/documents/{doc_id}/preview` — sets inline
disposition using the document filename
- **Improved** attachment download routing — resolves `mime_type` /
`ext` query params (no default `markdown`), supports
`disposition=inline`
- **DocGenerator output** — includes URL-encoded `preview_url` for MCP
clients
- **Legacy `/document/download/...` aliases** — still use download
semantics; MCP clients should call `/preview` explicitly

Fixes infiniflow#15398

## Test plan
- [x] `pytest test/unit_test/api/utils/test_file_response_headers.py`
(6/6)

---------

Co-authored-by: MkDev11 <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-authored-by: Ling Qin <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐖api The modified files are located under directory 'api/apps/sdk' ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. lgtm This PR has been approved by a maintainer size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Issue with MCP-Wrapped Agent: No File Preview via doc_id Query

5 participants