Skip to main content
Glama
itshare4u

Agent Knowledge MCP

delete_document

Remove a specific document from an Elasticsearch index using its document ID to manage stored data.

Instructions

Delete a document from Elasticsearch index by document ID

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
indexYesName of the Elasticsearch index containing the document
doc_idYesDocument ID to delete from the index

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The primary handler implementation for the 'delete_document' tool. Includes the @app.tool decorator for registration and input schema definition using Pydantic's Annotated and Field. Executes Elasticsearch delete operation with comprehensive error handling and user-friendly messages.
    @app.tool(
        description="Delete a document from Elasticsearch index by document ID",
        tags={"elasticsearch", "delete", "document"}
    )
    async def delete_document(
            index: Annotated[str, Field(description="Name of the Elasticsearch index containing the document")],
            doc_id: Annotated[str, Field(description="Document ID to delete from the index")]
    ) -> str:
        """Delete a document from Elasticsearch index."""
        try:
            es = get_es_client()
    
            result = es.delete(index=index, id=doc_id)
    
            return f"✅ Document deleted successfully:\n\n{json.dumps(result, indent=2, ensure_ascii=False)}"
    
        except Exception as e:
            # Provide detailed error messages for different types of Elasticsearch errors
            error_message = "❌ Failed to delete document:\n\n"
    
            error_str = str(e).lower()
            if "connection" in error_str or "refused" in error_str:
                error_message += "🔌 **Connection Error**: Cannot connect to Elasticsearch server\n"
                error_message += f"📍 Check if Elasticsearch is running at the configured address\n"
                error_message += f"💡 Try: Use 'setup_elasticsearch' tool to start Elasticsearch\n\n"
            elif (
                    "not_found" in error_str or "not found" in error_str or "does not exist" in error_str) or "index_not_found_exception" in error_str or "no such index" in error_str:
                # Check if it's specifically an index not found error
                if ("index" in error_str and (
                        "not found" in error_str or "not_found" in error_str or "does not exist" in error_str)) or "index_not_found_exception" in error_str or "no such index" in error_str:
                    error_message += f"📁 **Index Not Found**: Index '{index}' does not exist\n"
                    error_message += f"📍 The target index has not been created yet\n"
                    error_message += f"💡 Try: Use 'list_indices' to see available indices\n\n"
                else:
                    error_message += f"📄 **Document Not Found**: Document ID '{doc_id}' does not exist\n"
                    error_message += f"📍 Cannot delete a document that doesn't exist\n"
                    error_message += f"💡 Try: Check document ID or use 'search' to find documents\n\n"
            else:
                error_message += f"⚠️ **Unknown Error**: {str(e)}\n\n"
    
            error_message += f"🔍 **Technical Details**: {str(e)}"
    
            return error_message
  • Mounting/registration of the elasticsearch_document sub-server app (containing delete_document tool) into the unified Elasticsearch FastMCP server app.
    from .sub_servers.elasticsearch_document import app as document_app
    from .sub_servers.elasticsearch_index import app as index_app
    from .sub_servers.elasticsearch_search import app as search_app
    from .sub_servers.elasticsearch_batch import app as batch_app
    
    # Create unified FastMCP application
    app = FastMCP(
        name="AgentKnowledgeMCP-Elasticsearch",
        version="2.0.0",
        instructions="Unified Elasticsearch tools for comprehensive knowledge management via modular server mounting"
    )
    
    # ================================
    # SERVER MOUNTING - MODULAR ARCHITECTURE
    # ================================
    
    print("🏗️ Mounting Elasticsearch sub-servers...")
    
    # Mount all sub-servers into unified interface
    app.mount(snapshots_app)           # 3 tools: snapshot management
    app.mount(index_metadata_app)      # 3 tools: metadata governance  
    app.mount(document_app)            # 3 tools: document operations
    app.mount(index_app)               # 3 tools: index management
    app.mount(search_app)              # 2 tools: search & validation
    app.mount(batch_app)               # 2 tools: batch operations
  • Mounting of the unified elasticsearch_server_app (which includes the delete_document tool via sub-server mounting) into the main FastMCP server.
    # Mount Elasticsearch server with 'es' prefix
    # This provides: es_search, es_index_document, es_create_index, etc.
    app.mount(elasticsearch_server_app)
    
    # Mount Administrative operations server with 'admin' prefix
    # This provides: admin_get_config, admin_update_config, admin_server_status, etc.
    app.mount(admin_server_app)
    
    # Mount Prompt server for AgentKnowledgeMCP guidance
    # This provides: usage_guide, help_request (prompts for LLM assistance)
    app.mount(prompt_server_app)
  • Configuration listing 'delete_document' as a destructive operation requiring user confirmation via the middleware system.
    "destructive_operations": {
        "tools": ["delete_file", "delete_directory", "delete_index", "delete_document"],
        "require_confirmation": True,
        "timeout_minutes": 30
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It states the tool performs a deletion but omits critical details: whether this is irreversible, what permissions are required, how errors are handled (e.g., if the document doesn't exist), or any rate limits. For a destructive operation, this is a significant gap in transparency.

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 a single, direct sentence with zero wasted words. It front-loads the core action ('Delete') and efficiently specifies the target and method ('a document from Elasticsearch index by document ID'), making it easy to parse and understand immediately.

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

Completeness3/5

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

Given the tool's complexity (a destructive operation with 2 parameters), the description is minimally complete but lacks depth. While an output schema exists (reducing need to explain return values), the absence of annotations and insufficient behavioral details leaves gaps in understanding the tool's full impact and usage context.

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

Parameters3/5

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

Schema description coverage is 100%, with both parameters (index and doc_id) clearly documented in the schema. The description adds no additional semantic context beyond what the schema provides (e.g., format examples or constraints), so it meets the baseline for adequate but not enhanced parameter understanding.

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 ('Delete') and resource ('a document from Elasticsearch index by document ID'), distinguishing it from sibling tools like delete_index (which deletes entire indices) or get_document (which retrieves documents). It precisely communicates the tool's function without ambiguity.

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 like delete_index or batch operations. It lacks context about prerequisites (e.g., needing an existing index/document), exclusions, or typical scenarios for document deletion, leaving the agent to infer usage from the tool name 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/itshare4u/AgentKnowledgeMCP'

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