Skip to main content
Glama

update_document

Modify existing documents in a knowledge base by replacing content and re-indexing for accurate retrieval in local RAG systems.

Instructions

Update an existing document in the knowledge base.

Removes old chunks and re-indexes with new content.

Args:
    filepath: Full path to the document file
    content: New content for the document

Returns:
    JSON string with update results

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filepathYes
contentYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The 'update_document_content' method in 'KnowledgeOrchestrator' handles the removal of old document chunks and re-indexing of updated content.
    def update_document_content(self, filepath: str, content: str) -> Dict[str, Any]:
        """Update an existing document. Removes old chunks and re-indexes."""
        filepath = Path(filepath)
        if not filepath.exists():
            return {"error": f"File not found: {filepath}"}
    
        # Resolve to absolute for consistent comparison with stored metadata
        filepath_resolved = str(filepath.resolve())
    
        doc_id = None
        for did, info in self._indexed_docs.items():
            stored = str(Path(info.get("source", "")).resolve())
            if stored == filepath_resolved:
                doc_id = did
                break
    
        old_chunks_removed = 0
        if doc_id:
            old_chunks_removed = self._remove_document_chunks(doc_id)
            del self._indexed_docs[doc_id]
    
        filepath.write_text(content, encoding="utf-8")
    
        doc = self.parser.parse_file(filepath)
        if not doc:
            self._save_metadata()
            return {"error": "Failed to parse updated content", "old_chunks_removed": old_chunks_removed}
    
        new_chunks_added, dedup_skipped = self._index_document(doc)
    
        try:
            file_stat = filepath.stat()
            file_mtime = datetime.fromtimestamp(file_stat.st_mtime).isoformat()
            file_size = file_stat.st_size
        except OSError:
            file_mtime = datetime.now().isoformat()
            file_size = 0
    
        self._indexed_docs[doc.id] = {
            "source": str(filepath),
            "category": doc.category,
            "format": doc.format,
            "chunks": new_chunks_added,
            "keywords": doc.keywords,
            "indexed_at": datetime.now().isoformat(),
            "file_mtime": file_mtime,
            "file_size": file_size,
        }
        self._save_metadata()
        self.query_cache.invalidate()
        self.bm25_index.build_index()
    
        return {
            "old_chunks_removed": old_chunks_removed,
            "new_chunks_added": new_chunks_added,
            "dedup_skipped": dedup_skipped,
            "filepath": str(filepath),
        }
  • The MCP tool 'update_document' registration and entry point.
    def update_document(filepath: str, content: str) -> str:
        """
        Update an existing document in the knowledge base.
    
        Removes old chunks and re-indexes with new content.
    
        Args:
            filepath: Full path to the document file
            content: New content for the document
    
        Returns:
            JSON string with update results
        """
        if not filepath:
            return json.dumps({"status": "error", "message": "Filepath required"})
        if not content or not content.strip():
            return json.dumps({"status": "error", "message": "Content cannot be empty"})
    
        orchestrator = get_orchestrator()
        result = orchestrator.update_document_content(filepath, content.strip())
    
        if "error" in result:
            return json.dumps({"status": "error", "message": result["error"]})
    
        return json.dumps({"status": "success", **result}, indent=2)
Behavior3/5

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

With no annotations provided, the description carries the full burden. It discloses key behavioral traits: 'Removes old chunks and re-indexes with new content' explains the mutation process and side effects. It also mentions the return format ('JSON string with update results'). However, it lacks details on permissions, error handling, or performance implications.

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

Conciseness4/5

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

The description is appropriately sized and front-loaded: the first sentence states the purpose, followed by behavioral details and parameter/return explanations. Each sentence adds value, with no redundant information. Minor improvement could be made by integrating parameter details more seamlessly.

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 the tool's moderate complexity (mutation with 2 params), no annotations, but an output schema exists, the description is reasonably complete. It covers purpose, behavior, parameters, and returns, though it omits error cases and sibling differentiation. The output schema reduces the need to detail return values, so gaps are acceptable.

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

Parameters4/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 compensate. It adds meaning for both parameters: 'filepath: Full path to the document file' and 'content: New content for the document', clarifying their roles beyond the schema's basic titles. This adequately covers the two required parameters, though it doesn't specify format constraints (e.g., filepath syntax).

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

Purpose4/5

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

The description clearly states the tool's purpose: 'Update an existing document in the knowledge base.' It specifies the verb ('update') and resource ('document in the knowledge base'), distinguishing it from siblings like 'add_document' or 'remove_document'. However, it doesn't explicitly differentiate from 'reindex_documents' which might have overlapping functionality.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention prerequisites (e.g., document must exist), exclusions, or comparisons with siblings like 'reindex_documents' or 'add_document'. The agent must infer usage from the purpose alone.

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/lyonzin/knowledge-rag'

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