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

## 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
- [x] `pytest test/unit_test/api/utils/test_file_response_headers.py`
(6/6)

---------

Co-authored-by: MkDev11 <mkdev11@users.noreply.github.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Ling Qin <qinling0210@163.com>
This commit is contained in:
monsterDavid
2026-07-03 04:56:01 -07:00
committed by GitHub
parent 0f4f2135f3
commit 7da4f200e5
8 changed files with 295 additions and 106 deletions

View File

@@ -27,7 +27,11 @@ import time
from functools import partial, wraps
from typing import Set
from api.utils.web_utils import CONTENT_TYPE_MAP, apply_safe_file_response_headers
from api.utils.file_response import (
apply_download_file_response_headers,
apply_preview_file_response_headers,
resolve_attachment_content_type,
)
import jwt
from quart import Response, jsonify, request, make_response
@@ -2463,37 +2467,51 @@ async def webhook_trace(agent_id: str):
}
)
def _attachment_request_metadata():
ext = request.args.get("ext")
mime_type = request.args.get("mime_type")
filename = request.args.get("filename")
content_type, resolved_ext = resolve_attachment_content_type(ext, mime_type)
if not content_type:
content_type = "application/octet-stream"
if not resolved_ext:
resolved_ext = ext.lower().strip(".") if isinstance(ext, str) and ext else "bin"
return content_type, resolved_ext, filename
async def _stream_agent_attachment(tenant_id, attachment_id, *, inline: bool):
attachment_id = attachment_id or request.view_args.get("attachment_id")
content_type, ext, filename = _attachment_request_metadata()
data = await thread_pool_exec(settings.STORAGE_IMPL.get, tenant_id, attachment_id)
if not data:
return get_data_error_result(message="Document not found!")
response = await make_response(data)
if inline:
apply_preview_file_response_headers(response, content_type, ext, filename)
else:
apply_download_file_response_headers(response, content_type, ext, filename)
return response
@manager.route("/agents/attachments/<attachment_id>/preview", methods=["GET"]) # noqa: F821
@login_required
@add_tenant_id_to_kwargs
async def preview_attachment(tenant_id=None, attachment_id=None):
"""Stream an agent-generated attachment for inline preview in MCP clients."""
try:
return await _stream_agent_attachment(tenant_id, attachment_id, inline=True)
except Exception as e:
return server_error_response(e)
@manager.route("/agents/attachments/<attachment_id>/download", methods=["GET"]) # noqa: F821
@login_required
@add_tenant_id_to_kwargs
async def download_attachment(tenant_id=None, attachment_id=None):
"""Stream a document's underlying file to the requesting user.
Mirrors the authorization model of the preview endpoint: the user must belong
to the tenant that owns the document's knowledge base. A denial returns the
same "Attachment not found!" response so the endpoint cannot be used to
enumerate doc ids across tenants.
"""
"""Stream an agent-generated attachment as a download."""
try:
# Keep backward compatibility with older callers and unit tests that still
# pass `attachment_id` instead of the route parameter name.
ext = request.args.get("ext", "markdown")
data = await thread_pool_exec(settings.STORAGE_IMPL.get, tenant_id, attachment_id)
if not data:
# Storage object missing or empty (orphaned DB metadata, tenant
# mismatch). Without this guard `make_response(None)` raises
# `TypeError: response value cannot be None` and the caller
# sees HTTP 500 — same bug class as #15365 on document
# preview. Return the same "Attachment not found!" shape used
# by the preview route's missing-record path so byte-streaming
# endpoints respond consistently on a not-found.
return get_data_error_result(message="Attachment not found!")
response = await make_response(data)
content_type = CONTENT_TYPE_MAP.get(ext, f"application/{ext}")
apply_safe_file_response_headers(response, content_type, ext)
return response
if request.args.get("disposition", "").lower() == "inline":
return await _stream_agent_attachment(tenant_id, attachment_id, inline=True)
return await _stream_agent_attachment(tenant_id, attachment_id, inline=False)
except Exception as e:
return server_error_response(e)

View File

@@ -72,6 +72,7 @@ from common.constants import ParserType, RetCode, TaskStatus, SANDBOX_ARTIFACT_B
from common.metadata_utils import convert_conditions, meta_filter, turn2jsonschema
from common.misc_utils import get_uuid, thread_pool_exec
from api.utils.file_utils import filename_type, thumbnail
from api.utils.file_response import apply_preview_file_response_headers
from api.utils.web_utils import CONTENT_TYPE_MAP, html2pdf, is_valid_url, apply_safe_file_response_headers
from common.ssrf_guard import assert_url_is_safe
from rag.nlp import search
@@ -2088,7 +2089,7 @@ async def get(doc_id):
if ext:
fallback_prefix = "image" if doc.type == FileType.VISUAL.value else "application"
content_type = CONTENT_TYPE_MAP.get(ext, f"{fallback_prefix}/{ext}")
apply_safe_file_response_headers(response, content_type, ext)
apply_preview_file_response_headers(response, content_type, ext, doc.name)
return response
except Exception as e:
return server_error_response(e)