Skip to main content
Glama

reembed_document

Regenerate embeddings for document chunks in Paperlib MCP to update vector representations for improved semantic search and analysis.

Instructions

重新生成文档的 embedding

为文档的 chunks 生成 embedding。默认只处理缺失 embedding 的 chunks, 设置 force=True 可重新生成所有 embedding。

Args: doc_id: 文档的唯一标识符 batch_size: 批处理大小,默认 64 force: 是否强制重新生成所有 embedding,默认 False

Returns: 处理结果,包含处理的 chunk 数量

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
doc_idYes
batch_sizeNo
forceNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The core handler function for the 'reembed_document' MCP tool. It re-generates embeddings for a document's chunks (optionally forcing all), using batch processing and storing in the database.
    @mcp.tool()
    def reembed_document(
        doc_id: str,
        batch_size: int = 64,
        force: bool = False,
    ) -> dict[str, Any]:
        """重新生成文档的 embedding
        
        为文档的 chunks 生成 embedding。默认只处理缺失 embedding 的 chunks,
        设置 force=True 可重新生成所有 embedding。
        
        Args:
            doc_id: 文档的唯一标识符
            batch_size: 批处理大小,默认 64
            force: 是否强制重新生成所有 embedding,默认 False
            
        Returns:
            处理结果,包含处理的 chunk 数量
        """
        try:
            # 检查文档是否存在
            doc = query_one(
                "SELECT doc_id FROM documents WHERE doc_id = %s",
                (doc_id,)
            )
            
            if not doc:
                return {
                    "success": False,
                    "error": f"Document not found: {doc_id}",
                    "doc_id": doc_id,
                }
            
            settings = get_settings()
            
            # 查找需要处理的 chunks
            if force:
                # 删除现有 embeddings
                execute(
                    """
                    DELETE FROM chunk_embeddings 
                    WHERE chunk_id IN (SELECT chunk_id FROM chunks WHERE doc_id = %s)
                    """,
                    (doc_id,)
                )
                chunks = query_all(
                    "SELECT chunk_id, text FROM chunks WHERE doc_id = %s ORDER BY chunk_index",
                    (doc_id,)
                )
            else:
                # 只查找缺失 embedding 的 chunks
                chunks = query_all(
                    """
                    SELECT c.chunk_id, c.text 
                    FROM chunks c
                    LEFT JOIN chunk_embeddings ce ON c.chunk_id = ce.chunk_id
                    WHERE c.doc_id = %s AND ce.chunk_id IS NULL
                    ORDER BY c.chunk_index
                    """,
                    (doc_id,)
                )
            
            if not chunks:
                return {
                    "success": True,
                    "doc_id": doc_id,
                    "processed_chunks": 0,
                    "message": "No chunks need embedding",
                }
            
            # 批量生成 embeddings
            chunk_ids = [c["chunk_id"] for c in chunks]
            texts = [c["text"] for c in chunks]
            embeddings = get_embeddings_chunked(texts, batch_size=batch_size)
            
            # 写入数据库
            embedded_count = 0
            with get_db() as conn:
                with conn.cursor() as cur:
                    for chunk_id, embedding in zip(chunk_ids, embeddings):
                        embedding_str = "[" + ",".join(str(x) for x in embedding) + "]"
                        cur.execute(
                            """
                            INSERT INTO chunk_embeddings (chunk_id, embedding_model, embedding)
                            VALUES (%s, %s, %s::vector)
                            ON CONFLICT (chunk_id) DO UPDATE SET
                                embedding_model = EXCLUDED.embedding_model,
                                embedding = EXCLUDED.embedding
                            """,
                            (chunk_id, settings.embedding_model, embedding_str)
                        )
                        embedded_count += 1
            
            return {
                "success": True,
                "doc_id": doc_id,
                "processed_chunks": embedded_count,
                "total_chunks": len(chunks),
                "embedding_model": settings.embedding_model,
            }
            
        except Exception as e:
            return {
                "success": False,
                "error": str(e),
                "doc_id": doc_id,
            }
  • Top-level registration call that registers the fetch tools module, including reembed_document, on the MCP server instance.
    register_fetch_tools(mcp)
  • Module-level registration function that defines and registers all fetch tools (including reembed_document via @mcp.tool() decorators) to the MCP instance.
    def register_fetch_tools(mcp: FastMCP) -> None:
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden. It discloses key behavioral traits: the default selective processing of missing embeddings, the optional force regeneration, and batch processing capability. However, it doesn't mention potential side effects (e.g., performance impact), authentication needs, rate limits, or what happens to existing embeddings when force=False.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is efficiently structured with a purpose statement, usage clarification for the force parameter, and organized parameter explanations. Every sentence adds value without redundancy, and key information is front-loaded in the first two sentences.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given 3 parameters with 0% schema coverage and no annotations, the description does an excellent job explaining parameters and basic behavior. The presence of an output schema means return values don't need description. However, for a tool that modifies embeddings (implied mutation), additional context about permissions, idempotency, or error cases would enhance completeness.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must fully compensate. It provides clear semantic explanations for all three parameters: doc_id identifies the document, batch_size controls processing granularity with default, and force determines regeneration scope. This adds essential meaning beyond the bare schema types.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific action ('重新生成文档的 embedding' - regenerate document embeddings) and resource ('文档的 chunks' - document chunks). It distinguishes from potential siblings by specifying it generates embeddings for chunks, unlike tools like 'rechunk_document' or 'get_document_chunks' which handle chunk structure or retrieval.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides clear context about when to use force=True vs. the default behavior (only missing embeddings). However, it doesn't explicitly mention when NOT to use this tool or name specific alternatives among the many sibling tools, though the purpose is distinct enough to imply usage scenarios.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/h-lu/paperlib-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server