Skip to main content
Glama
itshare4u

Agent Knowledge MCP

delete_index

Remove an Elasticsearch index and all its documents permanently to manage storage and maintain data organization.

Instructions

Delete an Elasticsearch index and all its documents permanently

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
indexYesName of the Elasticsearch index to delete

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The core handler function for the 'delete_index' tool. It checks for index metadata, deletes the Elasticsearch index using es.indices.delete(), and provides detailed success/error messages with governance checks.
    @app.tool(
        description="Delete an Elasticsearch index and all its documents permanently",
        tags={"elasticsearch", "delete", "index", "destructive"}
    )
    async def delete_index(
            index: Annotated[str, Field(description="Name of the Elasticsearch index to delete")]
    ) -> str:
        """Delete an Elasticsearch index permanently."""
        try:
            es = get_es_client()
    
            # Check if metadata document exists for this index
            metadata_index = "index_metadata"
            try:
                # Search for existing metadata document
                search_body = {
                    "query": {
                        "term": {
                            "index_name.keyword": index
                        }
                    },
                    "size": 1
                }
    
                metadata_result = es.search(index=metadata_index, body=search_body)
    
                if metadata_result['hits']['total']['value'] > 0:
                    metadata_doc = metadata_result['hits']['hits'][0]
                    metadata_id = metadata_doc['_id']
                    metadata_source = metadata_doc['_source']
    
                    return (f"❌ Index deletion blocked - Metadata cleanup required!\n\n" +
                            f"🚨 **MANDATORY: Remove Index Metadata First**:\n" +
                            f"   📋 **Found Metadata Document**: {metadata_id}\n" +
                            f"   📝 **Index Description**: {metadata_source.get('description', 'No description')}\n" +
                            f"   🔧 **Required Action**: Delete metadata document before removing index\n\n" +
                            f"💡 **Cleanup Workflow**:\n" +
                            f"   1. Call 'delete_index_metadata' with index name '{index}'\n" +
                            f"   2. Then call 'delete_index' again to remove the actual index\n" +
                            f"   3. This ensures proper cleanup and audit trail\n\n" +
                            f"📊 **Metadata Details**:\n" +
                            f"   • Purpose: {metadata_source.get('purpose', 'Not specified')}\n" +
                            f"   • Data Types: {', '.join(metadata_source.get('data_types', []))}\n" +
                            f"   • Created: {metadata_source.get('created_date', 'Unknown')}\n" +
                            f"   • Usage: {metadata_source.get('usage_pattern', 'Not specified')}\n\n" +
                            f"🎯 **Why This Matters**:\n" +
                            f"   • Maintains clean metadata registry\n" +
                            f"   • Prevents orphaned documentation\n" +
                            f"   • Ensures proper audit trail for deletions\n" +
                            f"   • Confirms intentional removal with full context")
    
            except Exception as metadata_error:
                # If metadata index doesn't exist, warn but allow deletion
                if "index_not_found" in str(metadata_error).lower():
                    # Proceed with deletion but warn about missing metadata system
                    result = es.indices.delete(index=index)
    
                    return (f"⚠️ Index '{index}' deleted but metadata system is missing:\n\n" +
                            f"{json.dumps(result, indent=2, ensure_ascii=False)}\n\n" +
                            f"🚨 **Warning**: No metadata tracking system found\n" +
                            f"   📋 Consider setting up 'index_metadata' index for better governance\n" +
                            f"   💡 Use 'create_index_metadata' tool for future index documentation")
    
            # If we get here, no metadata found - proceed with deletion
            result = es.indices.delete(index=index)
    
            return f"✅ Index '{index}' 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 index:\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 "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"📍 Cannot delete an index that doesn't exist\n"
                error_message += f"💡 Try: Use 'list_indices' to see available indices\n\n"
            elif "permission" in error_str or "forbidden" in error_str:
                error_message += "🔒 **Permission Error**: Not allowed to delete index\n"
                error_message += f"📍 Insufficient permissions for index deletion\n"
                error_message += f"💡 Try: Check Elasticsearch security settings\n\n"
            else:
                error_message += f"⚠️ **Unknown Error**: {str(e)}\n\n"
    
            error_message += f"🔍 **Technical Details**: {str(e)}"
    
            return error_message
  • Mounting of the elasticsearch_index sub-server into the unified Elasticsearch server, registering the delete_index tool among others.
    # Import sub-server applications for mounting
    from .sub_servers.elasticsearch_snapshots import app as snapshots_app
    from .sub_servers.elasticsearch_index_metadata import app as index_metadata_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 into the main AgentKnowledgeMCP server, making the delete_index tool available in the primary server interface.
    print("🏗️ Mounting individual servers into main 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)
  • Pydantic schema definition for the 'delete_index' tool input parameter using Annotated and Field for validation and documentation.
    index: Annotated[str, Field(description="Name of the Elasticsearch index to delete")]
  • Documentation of tool distribution in sub-servers package, confirming delete_index is part of elasticsearch_index server.
    "elasticsearch_index": 3,          # list_indices, create_index, delete_index
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 action is 'permanent' which is crucial context, but doesn't mention required permissions, whether the operation is reversible, potential impacts on dependent resources, error conditions, or confirmation requirements. For a destructive operation with zero annotation coverage, this leaves significant behavioral gaps.

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, efficient sentence that communicates the core purpose with zero wasted words. It's appropriately sized for a single-parameter tool and front-loads the essential information about what the tool does and its permanent nature.

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 this is a destructive operation with no annotations but with an output schema (which presumably handles return values), the description provides the minimum viable information about what the tool does. However, for a permanent deletion tool, it should ideally include more warnings about data loss, prerequisites, or confirmation requirements to be considered complete.

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?

The schema description coverage is 100% (the single parameter 'index' is fully described in the schema as 'Name of the Elasticsearch index to delete'), so the baseline is 3. The description doesn't add any additional parameter semantics beyond what the schema already provides, such as index naming conventions, wildcard support, or validation rules.

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 target resource ('an Elasticsearch index and all its documents'), distinguishing it from sibling tools like delete_document (which deletes individual documents) and delete_index_metadata (which deletes metadata only). The inclusion of 'permanently' adds important scope information.

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

Usage Guidelines3/5

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

The description implies this should be used for deleting entire indices rather than individual documents (contrasted with delete_document), but doesn't explicitly state when to use this vs. alternatives like delete_index_metadata or provide guidance on prerequisites, recovery options, or warnings about data loss. The context is implied but not explicitly articulated.

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