Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat(pageindex): agentic retrieval via MCP tools + full document-endpoint format support

BukeLy2e82ad4d27df
diff --git a/deeptutor/agents/chat/agentic_pipeline.py b/deeptutor/agents/chat/agentic_pipeline.py
index 370684652..b71a5c602 100644
--- a/deeptutor/agents/chat/agentic_pipeline.py
+++ b/deeptutor/agents/chat/agentic_pipeline.py
@@ -442,6 +442,7 @@ class AgenticChatPipeline:
return str((context.metadata or {}).get("source") or "") == "partner"
async def _prepare_deferred_tools(self, context: UnifiedContext) -> None:
+ self._pageindex_docs = {}
try:
from deeptutor.services.mcp import get_mcp_manager, load_loaded_tools
@@ -460,6 +461,25 @@ class AgenticChatPipeline:
)
user_allowed = None if self._is_partner_turn(context) else allowed_mcp_tools()
allowed: set[str] | None = combine_whitelists(caller_allowed, user_allowed)
+
+ # Narrowed implicit grant: a turn with a PageIndex KB
+ # attached is authorized to use the built-in pageindex MCP
+ # server's tools — access to the KB is the permission. The tools
+ # are also preloaded (no load_tools round-trip) so retrieval
+ # works on the first turn.
+ self._pageindex_docs = self._pageindex_doc_maps(context)
+ pageindex_tools: set[str] = set()
+ if self._pageindex_docs:
+ from deeptutor.services.mcp.pageindex_server import PAGEINDEX_SERVER_NAME
+
+ pageindex_tools = {
+ t.get_definition().name
+ for t in self.registry.deferred_tools()
+ if getattr(t, "server_name", "") == PAGEINDEX_SERVER_NAME
+ }
+ if allowed is not None:
+ allowed = allowed | pageindex_tools
+
pool = self.registry.deferred_tools()
if allowed is not None:
pool = [t for t in pool if t.get_definition().name in allowed]
@@ -470,13 +490,32 @@ class AgenticChatPipeline:
self._deferred_loader = DeferredToolLoader(
registry=self.registry,
session_id=context.session_id,
- loaded=load_loaded_tools(context.session_id),
+ loaded=load_loaded_tools(context.session_id) | pageindex_tools,
allowed=allowed,
)
except Exception:
logger.warning("deferred-tool preparation failed", exc_info=True)
self._deferred_loader = None
+ def _pageindex_doc_maps(self, context: UnifiedContext) -> dict[str, dict[str, str]]:
+ """kb_name -> {file: doc_id} for bound KBs on the pageindex provider."""
+ out: dict[str, dict[str, str]] = {}
+ for kb in self._selected_kbs(context):
+ try:
+ from deeptutor.multi_user.knowledge_access import resolve_kb
+ from deeptutor.services.rag.factory import PAGEINDEX_PROVIDER
+ from deeptutor.services.rag.pipelines.pageindex.pipeline import PageIndexPipeline
+ from deeptutor.services.rag.provider_binding import resolve_bound_provider
+
+ resource = resolve_kb(kb, require_write=False)
+ base_dir = str(resource.base_dir)
+ if resolve_bound_provider(base_dir, resource.name) != PAGEINDEX_PROVIDER:
+ continue
+ out[kb] = PageIndexPipeline(kb_base_dir=base_dir).document_map(resource.name)
+ except Exception:
+ logger.debug("pageindex doc-map resolution failed for %r", kb, exc_info=True)
+ return out
+
def _deferred_tools_manifest(self) -> str:
if self._deferred_loader is None:
return ""
@@ -525,7 +564,9 @@ class AgenticChatPipeline:
requested_tools=context.enabled_tools,
optional_whitelist=CHAT_OPTIONAL_TOOLS,
mount_flags=ToolMountFlags(
- has_kb=bool(self._selected_kbs(context)),
+ # PageIndex KBs are read via the preloaded MCP tools, not rag —
+ # a conversation with only PageIndex KBs doesn't mount rag at all.
+ has_kb=bool(self._rag_kbs(context)),
# read_source is owned by the explore_context pre-pass (it runs
# the investigation over attached sources), not the answer loop.
# Keep it off the answer surface even when sources are present.
@@ -631,7 +672,7 @@ class AgenticChatPipeline:
context: UnifiedContext,
) -> list[dict[str, Any]]:
schemas = self.registry.build_openai_schemas(enabled_tools)
- kb_choices = self._selected_kbs(context)
+ kb_choices = self._rag_kbs(context)
notebook_choices = self._notebook_choices()
for schema in schemas:
function = schema.get("function") if isinstance(schema, dict) else None
@@ -1218,6 +1259,11 @@ class AgenticChatPipeline:
def _selected_kbs(context: UnifiedContext) -> list[str]:
return [str(kb).strip() for kb in context.knowledge_bases if str(kb).strip()]
+ def _rag_kbs(self, context: UnifiedContext) -> list[str]:
+ """Attached KBs served by the rag tool (PageIndex KBs are read via MCP)."""
+ pageindex = getattr(self, "_pageindex_docs", None) or {}
+ return [kb for kb in self._selected_kbs(context) if kb not in pageindex]
+
@staticmethod
def _workspace_key(context: UnifiedContext) -> str:
raw = str(
@@ -1232,13 +1278,52 @@ class AgenticChatPipeline:
def _kb_system_note(self, context: UnifiedContext) -> str:
if self._exclusive_capability_active(context):
return ""
- kbs = self._selected_kbs(context)
- if not kbs:
+ if not self._selected_kbs(context):
+ return ""
+ parts: list[str] = []
+ rag_kbs = self._rag_kbs(context)
+ if rag_kbs:
+ joined = ", ".join(rag_kbs)
+ if self.language == "zh":
+ parts.append(f"用户已挂载知识库:{joined}。调用 rag 时,kb_name 必须从其中选一个。")
+ else:
+ parts.append(
+ f"Attached knowledge bases: {joined}. When calling rag, kb_name "
+ "must be one of these names."
+ )
+ parts.append(self._pageindex_system_note())
+ return "".join(parts)
+
+ def _pageindex_system_note(self) -> str:
+ """Doc list + retrieval instructions for attached PageIndex KBs.
+
+ Populated by ``_prepare_deferred_tools`` once per turn, so the system
+ prompt stays byte-stable for the whole turn (KB cache prefix).
+ """
+ doc_maps = getattr(self, "_pageindex_docs", None) or {}
+ if not doc_maps:
return ""
- joined = ", ".join(kbs)
+ lines = []
+ for kb, doc_map in sorted(doc_maps.items()):
+ listed = "; ".join(
+ f"{name} (doc_id: {doc_id})" for name, doc_id in sorted(doc_map.items())
+ )
+ lines.append(f"- {kb}: {listed or '(no indexed documents)'}")
+ docs_block = "\n".join(lines)
if self.language == "zh":
- return f"用户已挂载知识库:{joined}。调用 rag 时,kb_name 必须从其中选一个。"
- return f"Attached knowledge bases: {joined}. When calling rag, kb_name must be one of these names."
+ return (
+ "\n以下知识库使用托管的 PageIndex 引擎,其文档通过已加载的 "
+ "PageIndex MCP 工具阅读:先用 mcp_pageindex_get_document_structure "
+ "查看结构,再用 mcp_pageindex_get_page_content 读取相关页面。文档清单:\n"
+ f"{docs_block}"
+ )
+ return (
+ "\nThe following knowledge bases are on the hosted PageIndex engine; read "
+ "their documents with the preloaded PageIndex MCP tools: "
+ "mcp_pageindex_get_document_structure for the outline, then "
+ "mcp_pageindex_get_page_content for the relevant pages. Documents:\n"
+ f"{docs_block}"
+ )
def _workspace_system_note(self, context: UnifiedContext) -> str:
if not getattr(self, "_exec_enabled", False):
diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.py
index d565ae415..2983beb54 100644
--- a/deeptutor/api/routers/knowledge.py
+++ b/deeptutor/api/routers/knowledge.py
@@ -586,7 +586,7 @@ def _assert_provider_ready(provider: str) -> None:
def _enforce_provider_formats(provider: str, files: list[UploadFile]) -> None:
- """PageIndex ingests PDF/Markdown only — reject other formats up front."""
+ """Reject files PageIndex's document endpoint does not accept, up front."""
if provider != PAGEINDEX_PROVIDER:
return
from deeptutor.services.rag.pipelines.pageindex.pipeline import SUPPORTED_EXTENSIONS
@@ -599,10 +599,11 @@ def _enforce_provider_formats(provider: str, files: list[UploadFile]) -> None:
and Path(f.filename).suffix.lower() not in SUPPORTED_EXTENSIONS
]
if unsupported:
+ supported = ", ".join(sorted(SUPPORTED_EXTENSIONS))
raise HTTPException(
status_code=400,
detail=(
- "PageIndex knowledge bases accept PDF and Markdown only. "
+ f"PageIndex knowledge bases accept: {supported}. "
f"Unsupported: {', '.join(unsupported[:5])}."
),
)
@@ -1046,6 +1047,16 @@ async def update_pageindex_pipeline_config(payload: PageIndexConfigUpdate):
api_base_url = payload.api_base_url.strip()
service.save_pageindex({"api_key": api_key, "api_base_url": api_base_url})
+
+ # The built-in pageindex MCP server derives its URL/Bearer header from
+ # these settings — resync connections so key changes apply immediately.
+ try:
+ from deeptutor.services.mcp import get_mcp_manager
+
+ await get_mcp_manager().reload()
+ except Exception:
+ logger.warning("MCP reload after PageIndex config change failed", exc_info=True)
+
return _pageindex_config_payload()
except Exception as e:
logger.error(f"Error updating PageIndex config: {e}")
diff --git a/deeptutor/services/mcp/config.py b/deeptutor/services/mcp/config.py
index 41afcee24..7da96e6f9 100644
--- a/deeptutor/services/mcp/config.py
+++ b/deeptutor/services/mcp/config.py
@@ -44,6 +44,9 @@ class MCPServerConfig(BaseModel):
# behaviour
tool_timeout: int = Field(default=30, ge=1, le=600)
enabled_tools: list[str] = Field(default_factory=lambda: ["*"])
+ # Blocklist applied after ``enabled_tools`` — for "everything except X"
+ # entries (used by the built-in pageindex server).
+ disabled_tools: list[str] = Field(default_factory=list)
enabled: bool = True
@field_validator("command", "url", "cwd", mode="before")
@@ -69,6 +72,9 @@ class MCPServerConfig(BaseModel):
)
def tool_allowed(self, raw_name: str, wrapped_name: str) -> bool:
+ blocked = set(self.disabled_tools or [])
+ if raw_name in blocked or wrapped_name in blocked:
+ return False
allowed = set(self.enabled_tools or ["*"])
return "*" in allowed or raw_name in allowed or wrapped_name in allowed
diff --git a/deeptutor/services/mcp/manager.py b/deeptutor/services/mcp/manager.py
index bc89b2364..f88c323eb 100644
--- a/deeptutor/services/mcp/manager.py
+++ b/deeptutor/services/mcp/manager.py
@@ -43,6 +43,7 @@ from deeptutor.services.mcp.config import (
MCPServerConfig,
load_mcp_config,
)
+from deeptutor.services.mcp.pageindex_server import with_builtin_servers
logger = logging.getLogger(__name__)
@@ -146,13 +147,13 @@ class MCPConnectionManager:
async with self._lock:
if self._started:
return
- await self._sync_to_config(load_mcp_config())
+ await self._sync_to_config(with_builtin_servers(load_mcp_config()))
self._started = True
async def reload(self) -> None:
"""Re-read the persisted config and apply the diff to live connections."""
async with self._lock:
- await self._sync_to_config(load_mcp_config())
+ await self._sync_to_config(with_builtin_servers(load_mcp_config()))
self._started = True
async def shutdown(self) -> None:
diff --git a/deeptutor/services/mcp/pageindex_server.py b/deeptutor/services/mcp/pageindex_server.py
new file mode 100644
index 000000000..e01de66ad
--- /dev/null
+++ b/deeptutor/services/mcp/pageindex_server.py
@@ -0,0 +1,52 @@
+"""Built-in PageIndex MCP server entry.
+
+PageIndex retrieval is agentic: the chat agent reads documents through the
+hosted PageIndex MCP server instead of a REST retrieval endpoint. When a
+PageIndex API key is configured, the connection manager overlays a reserved
+``pageindex`` server entry onto the user-editable MCP config at load time —
+it is never persisted to ``mcp.json``, and a user-defined server of the same
+name always wins. Credentials stay single-sourced in the pageindex runtime
+settings; saving a new key hot-reloads the connection (the Bearer header
+changes the connection signature).
+"""
+
+from __future__ import annotations
+
+from deeptutor.services.mcp.config import MCPConfig, MCPServerConfig
+
+PAGEINDEX_SERVER_NAME = "pageindex"
+
+# remove_document is the one api-proxy tool DeepTutor blocks: an agent
+# deleting a cloud doc would silently orphan the doc_ids in the local KB
+# manifest. Everything else the server advertises passes through.
+_BLOCKED_TOOLS = ["remove_document"]
+
+
+def builtin_pageindex_server() -> MCPServerConfig | None:
+ """The injected server entry, or ``None`` when no API key is configured."""
+ from deeptutor.services.rag.pipelines.pageindex.config import get_pageindex_config
+
+ try:
+ cfg = get_pageindex_config()
+ except Exception:
+ return None
+ return MCPServerConfig(
+ type="streamableHttp",
+ url=cfg.api_base_url.rstrip("/") + "/mcp",
+ headers={"Authorization": f"Bearer {cfg.api_key}"},
+ tool_timeout=120,
+ disabled_tools=list(_BLOCKED_TOOLS),
+ )
+
+
+def with_builtin_servers(config: MCPConfig) -> MCPConfig:
+ """Overlay code-injected servers onto *config*; user entries win."""
+ if PAGEINDEX_SERVER_NAME in config.servers:
+ return config
+ entry = builtin_pageindex_server()
+ if entry is None:
+ return config
+ return MCPConfig(servers={**config.servers, PAGEINDEX_SERVER_NAME: entry})
+
+
+__all__ = ["PAGEINDEX_SERVER_NAME", "builtin_pageindex_server", "with_builtin_servers"]
diff --git a/deeptutor/services/rag/pipelines/pageindex/client.py b/deeptutor/services/rag/pipelines/pageindex/client.py
index 7d59a7985..7413de58f 100644
--- a/deeptutor/services/rag/pipelines/pageindex/client.py
+++ b/deeptutor/services/rag/pipelines/pageindex/client.py
@@ -1,18 +1,15 @@
"""Thin async HTTP client for the hosted PageIndex REST API.
-We talk to the documented REST endpoints directly rather than the ``pageindex``
-SDK because the calls we need map 1:1 onto our per-KB pipeline contract:
+Upload and lifecycle only — retrieval happens agent-side through the PageIndex
+MCP server:
* ``POST /doc/`` — submit a document for processing → ``doc_id``
-* ``GET /doc/{doc_id}/`` — poll processing status / ``retrieval_ready``
-* ``POST /retrieval/`` — submit a doc-scoped, retrieval-only query
-* ``GET /retrieval/{id}/`` — poll for the retrieved nodes
+* ``GET /doc/{doc_id}/`` — poll processing status
* ``DELETE /doc/{doc_id}/`` — best-effort cloud cleanup
-Retrieval-only (not chat-completions) keeps generation on DeepTutor's own LLM
-("Option A"). The client keeps the dependency surface to ``httpx`` (already a
-dependency) and is trivially mockable: inject an ``httpx`` transport or swap the
-whole client out via ``PageIndexPipeline(client=...)`` in tests.
+The client keeps the dependency surface to ``httpx`` (already a dependency)
+and is trivially mockable: inject an ``httpx`` transport or swap the whole
+client out via ``PageIndexPipeline(client=...)`` in tests.
"""
from __future__ import annotations
@@ -20,7 +17,7 @@ from __future__ import annotations
import asyncio
import logging
from pathlib import Path
-from typing import Any, Callable, Optional
+from typing import Any, Optional
import httpx
@@ -91,9 +88,14 @@ class PageIndexClient:
raise PageIndexAPIError(f"submit_document returned no doc_id: {data!r}")
return str(doc_id)
- async def get_document(self, doc_id: str) -> dict[str, Any]:
+ async def get_document(self, doc_id: str, *, summary: bool = False) -> dict[str, Any]:
+ """GET /doc/{id}/ — status plus the document tree in ``result``.
+
+ ``summary=True`` asks the API to include per-node summaries.
+ """
+ params = {"summary": "true"} if summary else None
async with self._open() as client:
- resp = await client.get(f"/doc/{doc_id}/")
+ resp = await client.get(f"/doc/{doc_id}/", params=params)
return self._json(resp)
async def wait_until_ready(
@@ -102,15 +104,12 @@ class PageIndexClient:
*,
poll_interval: float = 3.0,
max_attempts: int = 200,
- on_poll: Optional[Callable[[int, str], None]] = None,
) -> dict[str, Any]:
- """Poll ``get_document`` until the document is retrieval-ready."""
- for attempt in range(max_attempts):
+ """Poll ``get_document`` until processing reaches a terminal state."""
+ for _ in range(max_attempts):
data = await self.get_document(doc_id)
status = str(data.get("status") or "").strip().lower()
ready = bool(data.get("retrieval_ready"))
- if on_poll is not None:
- on_poll(attempt, status or ("ready" if ready else "processing"))
if status in _TERMINAL_FAIL:
raise PageIndexAPIError(f"PageIndex processing failed for {doc_id}: {data!r}")
if ready or status in _TERMINAL_OK:
@@ -129,59 +128,5 @@ class PageIndexClient:
logger.warning("PageIndex delete_document(%s) failed: %s", doc_id, exc)
return False
- # ----- retrieval (query) ----------------------------------------------
-
- async def submit_retrieval(
- self, doc_id: str, query: str, *, thinking: bool = True
- ) -> dict[str, Any]:
- async with self._open() as client:
- resp = await client.post(
- "/retrieval/",
- json={"doc_id": doc_id, "query": query, "thinking": thinking},
- )
- return self._json(resp)
-
- async def get_retrieval(self, retrieval_id: str) -> dict[str, Any]:
- async with self._open() as client:
- resp = await client.get(f"/retrieval/{retrieval_id}/")
- return self._json(resp)
-
- async def retrieve(
- self,
- doc_id: str,
- query: str,
- *,
- thinking: bool = True,
- poll_interval: float = 2.0,
- max_attempts: int = 90,
- ) -> list[dict[str, Any]]:
- """Submit a doc-scoped retrieval query and return its retrieved nodes.
-
- Tolerant of both the async submit→poll flow (``retrieval_id`` then poll)
- and deployments that return ``retrieved_nodes`` inline on submit.
- """
- submitted = await self.submit_retrieval(doc_id, query, thinking=thinking)
- if isinstance(submitted.get("retrieved_nodes"), list):
- return submitted["retrieved_nodes"]
-
- retrieval_id = submitted.get("retrieval_id") or submitted.get("id")
- if not retrieval_id:
- raise PageIndexAPIError(
- f"submit_retrieval returned neither nodes nor retrieval_id: {submitted!r}"
- )
-
- for _ in range(max_attempts):
- data = await self.get_retrieval(str(retrieval_id))
- status = str(data.get("status") or "").strip().lower()
- nodes = data.get("retrieved_nodes")
- if status in _TERMINAL_FAIL:
- raise PageIndexAPIError(f"PageIndex retrieval failed for {doc_id}: {data!r}")
- if status in _TERMINAL_OK or (isinstance(nodes, list) and nodes):
- return nodes if isinstance(nodes, list) else []
- await asyncio.sleep(poll_interval)
- raise PageIndexAPIError(
- f"PageIndex retrieval timed out for {doc_id} after {max_attempts} polls"
- )
-
__all__ = ["PageIndexClient", "PageIndexAPIError"]
diff --git a/deeptutor/services/rag/pipelines/pageindex/pipeline.py b/deeptutor/services/rag/pipelines/pageindex/pipeline.py
index c358b37d0..8b060a522 100644
--- a/deeptutor/services/rag/pipelines/pageindex/pipeline.py
+++ b/deeptutor/services/rag/pipelines/pageindex/pipeline.py
@@ -1,10 +1,12 @@
"""PageIndex cloud-backed RAG pipeline orchestration.
Implements the same contract as :class:`LlamaIndexPipeline` (see
-``..base.RAGPipeline``) but delegates indexing and retrieval to the hosted
-PageIndex service. Documents are uploaded for tree building; retrieval is
-doc-scoped and reasoning-based (no embeddings). DeepTutor's own chat LLM still
-writes the final answer from the returned context.
+``..base.RAGPipeline``) but delegates indexing to the hosted PageIndex
+service (tree building, no embeddings). PageIndex's REST retrieval endpoint
+is deprecated: deep retrieval is agentic — the chat agent reads documents
+through the PageIndex MCP server — while ``search()`` serves programmatic
+callers with each document's real tree outline (titles / pages / summaries)
+fetched over REST.
"""
from __future__ import annotations
@@ -23,16 +25,29 @@ from deeptutor.services.rag.index_versioning import (
from deeptutor.services.rag.kb_paths import resolve_kb_dir
from . import storage
-from .client import PageIndexAPIError, PageIndexClient
-from .config import get_pageindex_config
+from .client import PageIndexClient
+from .config import PageIndexNotConfiguredError, get_pageindex_config
logger = logging.getLogger(__name__)
DEFAULT_KB_BASE_DIR = str(get_runtime_data_root() / "knowledge_bases")
-# PageIndex ingests PDFs and Markdown; other formats are rejected upstream and
-# skipped defensively here.
-SUPPORTED_EXTENSIONS = {".pdf", ".md", ".markdown"}
+# Mirrors what PageIndex ``POST /doc/`` accepts (ZIP is handled upstream as a
+# container: members are extracted and validated individually). Other formats
+# are rejected upstream and skipped defensively here.
+SUPPORTED_EXTENSIONS = {
+ ".pdf",
+ ".md",
+ ".markdown",
+ ".txt",
+ ".docx",
+ ".doc",
+ ".pptx",
+ ".ppt",
+ ".xlsx",
+ ".xls",
+ ".csv",
+}
def is_supported_file(path: str | Path) -> bool:
@@ -121,9 +136,7 @@ class PageIndexPipeline:
supported = [fp for fp in file_paths if is_supported_file(fp)]
skipped = [fp for fp in file_paths if not is_supported_file(fp)]
for fp in skipped:
- self.logger.warning(
- "PageIndex skips unsupported file (PDF/Markdown only): %s", Path(fp).name
- )
+ self.logger.warning("PageIndex skips unsupported file type: %s", Path(fp).name)
if not supported:
return 0
@@ -142,15 +155,23 @@ class PageIndexPipeline:
# ----- retrieval ------------------------------------------------------
- async def search(self, query: str, kb_name: str, **kwargs) -> Dict[str, Any]:
- kwargs.pop("mode", None)
- top_k = int(kwargs.get("top_k", 5) or 5)
+ # ponytail: flat per-doc cap on the formatted outline; per-consumer
+ # budgets if a real need shows up.
+ TREE_CHARS_PER_DOC = 6000
+
+ async def search(self, query: str, kb_name: str, **_kwargs) -> Dict[str, Any]:
+ """Return each document's tree outline (titles / pages / summaries).
+
+ The deprecated REST retrieval endpoint is gone; deep, query-driven
+ retrieval is agentic via the PageIndex MCP tools in chat. For
+ programmatic callers this returns the documents' real structure as
+ context — shallow but honest grounding.
+ """
kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)
storage_dir = resolve_storage_dir_for_read(kb_dir, None)
- manifest = storage.read_manifest(storage_dir)
- ids = storage.doc_ids(manifest)
+ docs = self.document_map(kb_name)
- if storage_dir is None or not ids:
+ if storage_dir is None or not docs:
return {
"query": query,
"answer": (
@@ -163,41 +184,46 @@ class PageIndexPipeline:
"needs_reindex": True,
}
- # doc_id -> file_name for provenance labelling.
- id_to_name = {
- str(entry["doc_id"]): name
- for name, entry in storage.doc_entries(manifest).items()
- if isinstance(entry, dict) and entry.get("doc_id")
- }
-
- client = self._get_client()
try:
+ client = self._get_client()
results = await asyncio.gather(
- *(client.retrieve(doc_id, query) for doc_id in ids),
+ *(client.get_document(doc_id, summary=True) for doc_id in docs.values()),
return_exceptions=True,
)
- except Exception as exc: # pragma: no cover - gather itself rarely raises
- return self._error_result(query, exc)
+ except PageIndexNotConfiguredError as exc:
+ return {
+ "query": query,
+ "answer": str(exc),
+ "content": "",
+ "sources": [],
+ "provider": storage.PROVIDER,
+ "error_type": "not_configured",
+ }
+ parts: list[str] = []
sources: list[dict[str, Any]] = []
- context_parts: list[str] = []
errors: list[str] = []
- for doc_id, result in zip(ids, results):
- if isinstance(result, Exception):
+ for (file_name, doc_id), result in zip(docs.items(), results):
+ if isinstance(result, BaseException):
errors.append(str(result))
- self.logger.warning("PageIndex retrieval failed for %s: %s", doc_id, result)
+ self.logger.warning("PageIndex tree fetch failed for %s: %s", doc_id, result)
continue
- doc_name = id_to_name.get(doc_id, doc_id)
- for node in result[:top_k]:
- text, source = self._node_to_source(doc_name, node)
- if text:
- context_parts.append(text)
- sources.append(source)
+ outline, doc_sources = self._format_tree(file_name, doc_id, result.get("result"))
+ if outline:
+ parts.append(f"## {file_name}\n{outline}")
+ sources.extend(doc_sources)
- if not sources and errors:
- return self._error_result(query, PageIndexAPIError("; ".join(errors[:3])))
+ if not parts and errors:
+ return {
+ "query": query,
+ "answer": "; ".join(errors[:3]),
+ "content": "",
+ "sources": [],
+ "provider": storage.PROVIDER,
+ "error_type": "retrieval_error",
+ }
- content = "\n\n".join(context_parts)
+ content = "\n\n".join(parts)
return {
"query": query,
"answer": content,
@@ -206,60 +232,67 @@ class PageIndexPipeline:
"provider": storage.PROVIDER,
}
- @staticmethod
- def _node_to_source(doc_name: str, node: dict[str, Any]) -> tuple[str, dict[str, Any]]:
- if not isinstance(node, dict):
- text = str(node)
- return text, {
- "title": doc_name,
- "content": text[:200],
- "source": doc_name,
- "page": "",
- "chunk_id": "",
- "score": "",
- }
- title = node.get("title") or doc_name
- texts: list[str] = []
- pages: list[Any] = []
- for chunk in node.get("relevant_contents") or []:
- if isinstance(chunk, dict):
- piece = chunk.get("content") or chunk.get("text") or ""
- if piece:
- texts.append(str(piece))
- if chunk.get("page_index") is not None:
- pages.append(chunk.get("page_index"))
- elif chunk:
- texts.append(str(chunk))
- text = "\n".join(texts) or str(node.get("text") or node.get("content") or "")
- page = pages[0] if pages else node.get("page_index", "")
- source = {
- "title": title,
- "content": text[:200],
- "source": doc_name,
- "page": page if page is not None else "",
- "chunk_id": node.get("node_id") or "",
- "score": node.get("score", ""),
- }
- return text, source
-
- def _error_result(self, query: str, exc: Exception) -> Dict[str, Any]:
- from deeptutor.services.rag.pipelines.pageindex.config import (
- PageIndexNotConfiguredError,
- )
+ @classmethod
+ def _format_tree(
+ cls, file_name: str, doc_id: str, tree: Any
+ ) -> tuple[str, list[dict[str, Any]]]:
+ """Render a PageIndex tree as an indented outline + per-section sources."""
+ lines: list[str] = []
+ sources: list[dict[str, Any]] = []
- needs_config = isinstance(exc, PageIndexNotConfiguredError)
+ def walk(node: Any, depth: int) -> None:
+ if isinstance(node, list):
+ for item in node:
+ walk(item, depth)
+ return
+ if not isinstance(node, dict):
+ return
+ title = str(node.get("title") or "").strip()
+ page = node.get("page_index")
+ summary = str(node.get("summary") or node.get("prefix_summary") or "").strip()
+ if title:
+ line = f"{' ' * depth}- {title}"
+ if page not in (None, ""):
+ line += f" (p.{page})"
+ if summary:
+ line += f": {summary}"
+ lines.append(line)
+ if depth == 0:
+ sources.append(
+ {
+ "title": title,
+ "content": summary[:200],
+ "source": file_name,
+ "page": page if page is not None else "",
+ "chunk_id": node.get("node_id") or doc_id,
+ "score": "",
+ }
+ )
+ walk(node.get("nodes") or [], depth + 1)
+
+ walk(tree, 0)
+ text = "\n".join(lines)
+ if len(text) > cls.TREE_CHARS_PER_DOC:
+ text = text[: cls.TREE_CHARS_PER_DOC] + "\n… (outline truncated)"
+ return text, sources
+
+ def document_map(self, kb_name: str) -> dict[str, str]:
+ """file name -> cloud doc_id for the KB's current manifest.
+
+ Used by the chat layer to inject the doc list into the system prompt,
+ and embedded in the ``mcp_only`` search result.
+ """
+ kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)
+ manifest = storage.read_manifest(resolve_storage_dir_for_read(kb_dir, None))
return {
- "query": query,
- "answer": str(exc),
- "content": "",
- "sources": [],
- "provider": storage.PROVIDER,
- "error_type": "not_configured" if needs_config else "retrieval_error",
+ name: str(entry["doc_id"])
+ for name, entry in storage.doc_entries(manifest).items()
+ if isinstance(entry, dict) and entry.get("doc_id")
}
# ----- lifecycle ------------------------------------------------------
- async def delete(self, kb_name: str, **kwargs) -> bool:
+ async def delete(self, kb_name: str, **_kwargs) -> bool:
import shutil
kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)
diff --git a/tests/agents/chat/test_pageindex_mcp.py b/tests/agents/chat/test_pageindex_mcp.py
new file mode 100644
index 000000000..7b792e9f6
--- /dev/null
+++ b/tests/agents/chat/test_pageindex_mcp.py
@@ -0,0 +1,103 @@
+"""Chat-side PageIndex MCP wiring.
+
+Attaching a PageIndex KB grants the turn the built-in pageindex MCP server's
+tools (narrowed implicit grant), preloads them (no load_tools round-trip),
+and injects the KB's document list into the system prompt.
+"""
+
+from __future__ import annotations
+
+import asyncio
+
+from deeptutor.agents.chat.agentic_pipeline import AgenticChatPipeline
+from deeptutor.core.context import UnifiedContext
+from deeptutor.core.tool_protocol import BaseTool, ToolDefinition, ToolResult
+
+
+class FakeMCPTool(BaseTool):
+ deferred = True
+
+ def __init__(self, server: str, name: str) -> None:
+ self.server_name = server
+ self._name = f"mcp_{server}_{name}"
+
+ def get_definition(self) -> ToolDefinition:
+ return ToolDefinition(
+ name=self._name,
+ description="fake",
+ raw_parameters={"type": "object", "properties": {}},
+ )
+
+ async def execute(self, **kwargs) -> ToolResult: # pragma: no cover - unused
+ return ToolResult(content="")
+
+
+class FakeRegistry:
+ def __init__(self, tools: list[BaseTool]) -> None:
+ self._tools = {t.get_definition().name: t for t in tools}
+
+ def deferred_tools(self) -> list[BaseTool]:
+ return list(self._tools.values())
+
+ def get(self, name: str) -> BaseTool | None:
+ return self._tools.get(name)
+
+
+class FakeManager:
+ async def ensure_started(self) -> None:
+ return None
+
+
+def _prepare(monkeypatch, docs: dict[str, dict[str, str]]) -> AgenticChatPipeline:
+ pipe = AgenticChatPipeline(language="en")
+ pageindex_tool = FakeMCPTool("pageindex", "get_page_content")
+ other_tool = FakeMCPTool("other", "do_thing")
+ pipe.registry = FakeRegistry([pageindex_tool, other_tool])
+
+ monkeypatch.setattr("deeptutor.services.mcp.get_mcp_manager", lambda: FakeManager())
+ monkeypatch.setattr("deeptutor.services.mcp.load_loaded_tools", lambda _sid: set())
+ # Non-admin user without an MCP grant: fail-closed empty whitelist.
+ monkeypatch.setattr("deeptutor.multi_user.tool_access.allowed_mcp_tools", lambda: set())
+ monkeypatch.setattr(pipe, "_pageindex_doc_maps", lambda _ctx: docs)
+
+ ctx = UnifiedContext(knowledge_bases=list(docs))
+ asyncio.run(pipe._prepare_deferred_tools(ctx))
+ return pipe
+
+
+def test_pageindex_kb_grants_and_preloads_server_tools(monkeypatch) -> None:
+ pipe = _prepare(monkeypatch, {"kb1": {"a.pdf": "pi-1"}})
+
+ pool_names = {t.get_definition().name for t in pipe._deferred_pool}
+ # Implicit grant covers exactly the pageindex server, not other MCP tools.
+ assert pool_names == {"mcp_pageindex_get_page_content"}
+ # Preloaded: schema present without a load_tools round-trip.
+ assert pipe._deferred_loader is not None
+ preloaded = {s["function"]["name"] for s in pipe._deferred_loader.initial_schemas()}
+ assert "mcp_pageindex_get_page_content" in preloaded
+
+
+def test_no_pageindex_kb_keeps_fail_closed(monkeypatch) -> None:
+ pipe = _prepare(monkeypatch, {})
+ assert pipe._deferred_pool == []
+ assert pipe._deferred_loader is None
+
+
+def test_system_note_lists_documents(monkeypatch) -> None:
+ pipe = _prepare(monkeypatch, {"kb1": {"a.pdf": "pi-1", "b.docx": "pi-2"}})
+ note = pipe._kb_system_note(UnifiedContext(knowledge_bases=["kb1"]))
+ assert "mcp_pageindex_get_document_structure" in note
+ assert "a.pdf (doc_id: pi-1)" in note
+ assert "b.docx (doc_id: pi-2)" in note
+ # Pure-pageindex conversation: rag isn't mounted, so no rag wording at all.
+ assert "calling rag" not in note
+
+
+def test_rag_kbs_excludes_pageindex(monkeypatch) -> None:
+ pipe = _prepare(monkeypatch, {"kb1": {"a.pdf": "pi-1"}})
+ ctx = UnifiedContext(knowledge_bases=["kb1", "kb2"])
+ # kb1 is pageindex → excluded from the rag tool surface; kb2 stays.
+ assert pipe._rag_kbs(ctx) == ["kb2"]
+ note = pipe._kb_system_note(ctx)
+ assert "Attached knowledge bases: kb2." in note
+ assert "kb1" in note # listed in the PageIndex MCP block instead
diff --git a/tests/services/mcp/test_pageindex_server.py b/tests/services/mcp/test_pageindex_server.py
new file mode 100644
index 000000000..4f2f93e8c
--- /dev/null
+++ b/tests/services/mcp/test_pageindex_server.py
@@ -0,0 +1,68 @@
+"""Built-in pageindex MCP server injection."""
+
+from __future__ import annotations
+
+from deeptutor.services.mcp import pageindex_server
+from deeptutor.services.mcp.config import MCPConfig, MCPServerConfig
+from deeptutor.services.mcp.manager import wrapped_tool_name
+from deeptutor.services.rag.pipelines.pageindex.config import (
+ PageIndexConfig,
+ PageIndexNotConfiguredError,
+)
+
+
+def _configured(monkeypatch, key: str = "sk-test") -> None:
+ monkeypatch.setattr(
+ "deeptutor.services.rag.pipelines.pageindex.config.get_pageindex_config",
+ lambda **_: PageIndexConfig(api_key=key, api_base_url="https://api.pageindex.ai"),
+ )
+
+
+def _unconfigured(monkeypatch) -> None:
+ def _raise(**_):
+ raise PageIndexNotConfiguredError("no key")
+
+ monkeypatch.setattr(
+ "deeptutor.services.rag.pipelines.pageindex.config.get_pageindex_config", _raise
+ )
+
+
+def test_injects_builtin_server_when_configured(monkeypatch) -> None:
+ _configured(monkeypatch)
+ config = pageindex_server.with_builtin_servers(MCPConfig())
+ entry = config.servers["pageindex"]
+ assert entry.url == "https://api.pageindex.ai/mcp"
+ assert entry.headers["Authorization"] == "Bearer sk-test"
+ assert entry.resolved_type() == "streamableHttp"
+
+
+def test_no_injection_without_key(monkeypatch) -> None:
+ _unconfigured(monkeypatch)
+ config = pageindex_server.with_builtin_servers(MCPConfig())
+ assert "pageindex" not in config.servers
+
+
+def test_user_defined_entry_wins(monkeypatch) -> None:
+ _configured(monkeypatch)
+ user = MCPConfig(servers={"pageindex": MCPServerConfig(url="https://example.com/mcp")})
+ config = pageindex_server.with_builtin_servers(user)
+ assert config.servers["pageindex"].url == "https://example.com/mcp"
+
+
+def test_builtin_blocks_remove_document(monkeypatch) -> None:
+ _configured(monkeypatch)
+ entry = pageindex_server.builtin_pageindex_server()
+ assert entry is not None
+ assert not entry.tool_allowed(
+ "remove_document", wrapped_tool_name("pageindex", "remove_document")
+ )
+ # Everything else passes through untouched.
+ assert entry.tool_allowed(
+ "get_page_content", wrapped_tool_name("pageindex", "get_page_content")
+ )
+
+
+def test_disabled_tools_blocklist_beats_wildcard() -> None:
+ cfg = MCPServerConfig(url="https://x/mcp", disabled_tools=["bad_tool"])
+ assert not cfg.tool_allowed("bad_tool", wrapped_tool_name("x", "bad_tool"))
+ assert cfg.tool_allowed("good_tool", wrapped_tool_name("x", "good_tool"))
diff --git a/tests/services/rag/test_pageindex_pipeline.py b/tests/services/rag/test_pageindex_pipeline.py
index 22cb81551..ebe738af8 100644
--- a/tests/services/rag/test_pageindex_pipeline.py
+++ b/tests/services/rag/test_pageindex_pipeline.py
@@ -1,8 +1,9 @@
"""Unit tests for the PageIndex cloud RAG pipeline + provider routing.
The pipeline talks to PageIndex's REST API through an injectable client, so we
-exercise the orchestration (file filtering, manifest, fan-out merge, delete)
-against a fake client without any network calls.
+exercise the orchestration (file filtering, manifest, mcp_only search contract,
+delete) against a fake client without any network calls. Retrieval itself is
+agentic via the PageIndex MCP server and out of scope here.
"""
from __future__ import annotations
@@ -26,7 +27,7 @@ class FakeClient:
def __init__(self) -> None:
self.submitted: list[str] = []
self.deleted: list[str] = []
- self.retrieve_map: dict[str, list[dict]] = {}
+ self.trees: dict[str, list[dict]] = {}
async def submit_document(self, file_path) -> str:
self.submitted.append(str(file_path))
@@ -35,8 +36,13 @@ class FakeClient:
async def wait_until_ready(self, doc_id, **_kwargs) -> dict:
return {"status": "completed", "retrieval_ready": True}
- async def retrieve(self, doc_id, query, **_kwargs) -> list[dict]:
- return self.retrieve_map.get(doc_id, [])
+ async def get_document(self, doc_id, **_kwargs) -> dict:
+ return {
+ "doc_id": doc_id,
+ "status": "completed",
+ "retrieval_ready": True,
+ "result": self.trees.get(doc_id, []),
+ }
async def delete_document(self, doc_id) -> bool:
self.deleted.append(doc_id)
@@ -53,36 +59,36 @@ def _manifest(tmp_path, kb_name) -> dict:
def test_is_supported_file() -> None:
- assert is_supported_file("a.pdf")
- assert is_supported_file("b.MD")
- assert is_supported_file("c.markdown")
- assert not is_supported_file("d.docx")
- assert not is_supported_file("e.txt")
+ # Mirrors PageIndex POST /doc/ accepted formats.
+ for name in ("a.pdf", "b.MD", "c.markdown", "d.docx", "e.txt", "f.XLSX", "g.pptx", "h.csv"):
+ assert is_supported_file(name), name
+ assert not is_supported_file("i.png")
+ assert not is_supported_file("j.zip") # containers are unpacked upstream
def test_initialize_submits_supported_and_skips_others(tmp_path) -> None:
client = FakeClient()
pdf = tmp_path / "a.pdf"
pdf.write_text("x")
- md = tmp_path / "b.md"
- md.write_text("y")
- docx = tmp_path / "c.docx"
- docx.write_text("z")
+ docx = tmp_path / "b.docx"
+ docx.write_text("y")
+ png = tmp_path / "c.png"
+ png.write_text("z")
- ok = asyncio.run(_pipe(tmp_path, client).initialize("kb1", [str(pdf), str(md), str(docx)]))
+ ok = asyncio.run(_pipe(tmp_path, client).initialize("kb1", [str(pdf), str(docx), str(png)]))
assert ok is True
- assert sorted(Path(p).name for p in client.submitted) == ["a.pdf", "b.md"]
+ assert sorted(Path(p).name for p in client.submitted) == ["a.pdf", "b.docx"]
docs = _manifest(tmp_path, "kb1")["docs"]
- assert set(docs) == {"a.pdf", "b.md"}
+ assert set(docs) == {"a.pdf", "b.docx"}
assert docs["a.pdf"]["doc_id"] == "pi-a.pdf"
def test_initialize_no_supported_returns_false(tmp_path) -> None:
client = FakeClient()
- docx = tmp_path / "c.docx"
- docx.write_text("z")
- ok = asyncio.run(_pipe(tmp_path, client).initialize("kb2", [str(docx)]))
+ png = tmp_path / "c.png"
+ png.write_text("z")
+ ok = asyncio.run(_pipe(tmp_path, client).initialize("kb2", [str(png)]))
assert ok is False
assert client.submitted == []
@@ -102,28 +108,49 @@ def test_add_documents_appends_to_manifest(tmp_path) -> None:
assert set(_manifest(tmp_path, "kb")["docs"]) == {"a.pdf", "b.pdf"}
-def test_search_merges_nodes_into_sources(tmp_path) -> None:
+def test_search_returns_document_outline(tmp_path) -> None:
client = FakeClient()
pipe = _pipe(tmp_path, client)
pdf = tmp_path / "a.pdf"
pdf.write_text("x")
asyncio.run(pipe.initialize("kb", [str(pdf)]))
- client.retrieve_map["pi-a.pdf"] = [
+ client.trees["pi-a.pdf"] = [
{
"title": "Introduction",
"node_id": "n1",
- "relevant_contents": [{"page_index": 3, "content": "hello world"}],
+ "page_index": 1,
+ "prefix_summary": "What this paper is about.",
+ "nodes": [
+ {"title": "Background", "node_id": "n2", "page_index": 2, "summary": "History."}
+ ],
}
]
res = asyncio.run(pipe.search("what?", "kb"))
assert res["provider"] == "pageindex"
- assert "hello world" in res["content"]
+ assert "error_type" not in res
+ # Real structural context: nested outline with titles, pages, summaries.
+ assert "- Introduction (p.1): What this paper is about." in res["content"]
+ assert " - Background (p.2): History." in res["content"]
+ assert res["answer"] == res["content"]
+ # Sources come from top-level sections, anchored to the file.
assert res["sources"][0]["title"] == "Introduction"
- assert res["sources"][0]["page"] == 3
+ assert res["sources"][0]["page"] == 1
assert res["sources"][0]["source"] == "a.pdf"
+ assert res["sources"][0]["chunk_id"] == "n1"
+
+
+def test_document_map_exposes_manifest(tmp_path) -> None:
+ client = FakeClient()
+ pipe = _pipe(tmp_path, client)
+ pdf = tmp_path / "a.pdf"
+ pdf.write_text("x")
+ asyncio.run(pipe.initialize("kb", [str(pdf)]))
+
+ assert pipe.document_map("kb") == {"a.pdf": "pi-a.pdf"}
+ assert pipe.document_map("missing-kb") == {}
def test_search_without_documents_flags_reindex(tmp_path) -> None:
diff --git a/web/components/knowledge/CreateKbModal.tsx b/web/components/knowledge/CreateKbModal.tsx
index b63935aaf..34866af4d 100644
--- a/web/components/knowledge/CreateKbModal.tsx
+++ b/web/components/knowledge/CreateKbModal.tsx
@@ -24,7 +24,20 @@ import {
import { validateFiles } from "@/lib/knowledge-helpers";
import FileDropZone from "./FileDropZone";
-const PAGEINDEX_FORMATS = [".pdf", ".md", ".markdown"];
+// Mirrors SUPPORTED_EXTENSIONS in the backend pageindex pipeline (PageIndex POST /doc/).
+const PAGEINDEX_FORMATS = [
+ ".pdf",
+ ".md",
+ ".markdown",
+ ".txt",
+ ".docx",
+ ".doc",
+ ".pptx",
+ ".ppt",
+ ".xlsx",
+ ".xls",
+ ".csv",
+];
const OBSIDIAN_SOURCE = "obsidian";
const LIGHTRAG_SERVER_PROVIDER = "lightrag-server";
const EXAMPLE_INDEX_PATH = "/Users/you/knowledge_bases/my-kb";
@@ -550,7 +563,7 @@ function NewModeFields({
{t("Initial documents")}
{isPageIndex && (
<span className="ml-2 normal-case tracking-normal text-[var(--muted-foreground)]/80">
- · {t("PDF and Markdown only")}
+ · {t("PDF, Office, text and Markdown")}
</span>
)}
</label>
diff --git a/web/components/knowledge/EngineDetail.tsx b/web/components/knowledge/EngineDetail.tsx
index 8065ff220..e65702aec 100644
--- a/web/components/knowledge/EngineDetail.tsx
+++ b/web/components/knowledge/EngineDetail.tsx
@@ -135,7 +135,7 @@ const ENGINE_PREREQUISITES: Record<string, string> = {
llamaindex:
"Local vector engine — works out of the box. Retrieval uses your active embedding model; install the optional BM25 package to enable hybrid retrieval.",
pageindex:
- "Hosted engine: documents are uploaded to PageIndex's servers for processing. Requires an API key; PDF / Markdown only.",
+ "Hosted engine: documents are uploaded to PageIndex's servers and the chat agent reads them through the PageIndex MCP tools. Requires an API key; PDF, Office, text and Markdown formats.",
graphrag:
"Local knowledge-graph retrieval. Needs the optional dependency installed; indexing is LLM-heavy. Requires an active chat model and embedding model.",
lightrag:
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index dc8a3ebd2..f09ffdbf1 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -2421,7 +2421,7 @@
"Index engine": "Index engine",
"Needs key": "Needs key",
"This engine needs an API key. Configure it before creating.": "This engine needs an API key. Configure it before creating.",
- "PDF and Markdown only": "PDF and Markdown only",
+ "PDF, Office, text and Markdown": "PDF, Office, text and Markdown",
"PageIndex settings": "PageIndex settings",
"Get an API key": "Get an API key",
"PageIndex is a hosted, vectorless retrieval engine. Documents in a PageIndex knowledge base are uploaded to PageIndex's servers for processing. One key is shared by all your PageIndex knowledge bases.": "PageIndex is a hosted, vectorless retrieval engine. Documents in a PageIndex knowledge base are uploaded to PageIndex's servers for processing. One key is shared by all your PageIndex knowledge bases.",
@@ -2536,7 +2536,7 @@
"RAG-Anything package installed": "RAG-Anything package installed",
"Vision model for multimodal": "Vision model for multimodal",
"Local vector engine — works out of the box. Retrieval uses your active embedding model; install the optional BM25 package to enable hybrid retrieval.": "Local vector engine — works out of the box. Retrieval uses your active embedding model; install the optional BM25 package to enable hybrid retrieval.",
- "Hosted engine: documents are uploaded to PageIndex's servers for processing. Requires an API key; PDF / Markdown only.": "Hosted engine: documents are uploaded to PageIndex's servers for processing. Requires an API key; PDF / Markdown only.",
+ "Hosted engine: documents are uploaded to PageIndex's servers and the chat agent reads them through the PageIndex MCP tools. Requires an API key; PDF, Office, text and Markdown formats. Chat retrieval only.": "Hosted engine: documents are uploaded to PageIndex's servers and the chat agent reads them through the PageIndex MCP tools. Requires an API key; PDF, Office, text and Markdown formats. Chat retrieval only.",
"Local knowledge-graph retrieval. Needs the optional dependency installed; indexing is LLM-heavy. Requires an active chat model and embedding model.": "Local knowledge-graph retrieval. Needs the optional dependency installed; indexing is LLM-heavy. Requires an active chat model and embedding model.",
"Graph + vector retrieval with multimodal parsing. Needs the optional dependency installed; indexing is LLM-heavy. Requires active chat and embedding models; multimodal also needs a vision model.": "Graph + vector retrieval with multimodal parsing. Needs the optional dependency installed; indexing is LLM-heavy. Requires active chat and embedding models; multimodal also needs a vision model.",
"OCR scanned pages": "OCR scanned pages",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 60fbe1a8d..7a33af163 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -2421,7 +2421,7 @@
"Index engine": "索引引擎",
"Needs key": "需配置密钥",
"This engine needs an API key. Configure it before creating.": "该引擎需要 API 密钥,请先配置再创建。",
- "PDF and Markdown only": "仅支持 PDF 和 Markdown",
+ "PDF, Office, text and Markdown": "支持 PDF、Office、文本和 Markdown",
"PageIndex settings": "PageIndex 设置",
"Get an API key": "获取 API 密钥",
"PageIndex is a hosted, vectorless retrieval engine. Documents in a PageIndex knowledge base are uploaded to PageIndex's servers for processing. One key is shared by all your PageIndex knowledge bases.": "PageIndex 是托管的无向量检索引擎。PageIndex 知识库中的文档会上传到 PageIndex 服务器进行处理。同一个密钥由你所有的 PageIndex 知识库共用。",
@@ -2536,7 +2536,7 @@
"RAG-Anything package installed": "已安装 RAG-Anything 依赖包",
"Vision model for multimodal": "用于多模态的视觉模型",
"Local vector engine — works out of the box. Retrieval uses your active embedding model; install the optional BM25 package to enable hybrid retrieval.": "本地向量引擎,开箱即用。检索使用你当前启用的嵌入模型;可选安装 BM25 包以启用混合检索。",
- "Hosted engine: documents are uploaded to PageIndex's servers for processing. Requires an API key; PDF / Markdown only.": "托管引擎:文档会上传到 PageIndex 服务器处理。需配置 API 密钥;仅支持 PDF / Markdown。",
+ "Hosted engine: documents are uploaded to PageIndex's servers and the chat agent reads them through the PageIndex MCP tools. Requires an API key; PDF, Office, text and Markdown formats. Chat retrieval only.": "托管引擎:文档上传到 PageIndex 服务器,聊天 agent 通过 PageIndex MCP 工具阅读文档。需配置 API 密钥;支持 PDF、Office、文本和 Markdown 格式。仅支持对话内检索。",
"Local knowledge-graph retrieval. Needs the optional dependency installed; indexing is LLM-heavy. Requires an active chat model and embedding model.": "本地知识图谱检索。需要安装可选依赖;索引为 LLM 密集型操作。需启用对话模型与嵌入模型。",
"Graph + vector retrieval with multimodal parsing. Needs the optional dependency installed; indexing is LLM-heavy. Requires active chat and embedding models; multimodal also needs a vision model.": "图 + 向量检索,支持多模态解析。需要安装可选依赖;索引为 LLM 密集型操作。需启用对话与嵌入模型;多模态还需视觉模型。",
"OCR scanned pages": "对扫描页做 OCR",