Skip to main content
Glama
itshare4u

Agent Knowledge MCP

get_document

Retrieve a specific document from Elasticsearch by providing the index name and document ID to access stored information.

Instructions

Retrieve a specific document from Elasticsearch index by document ID

Input Schema

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

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The get_document tool handler: async function that uses Elasticsearch client to retrieve a document by index and doc_id. Includes input schema via Annotated[Field], JSON output formatting, and detailed error handling for connection issues, missing index, missing document, etc.
    @app.tool(
        description="Retrieve a specific document from Elasticsearch index by document ID",
        tags={"elasticsearch", "get", "document", "retrieve"}
    )
    async def get_document(
            index: Annotated[str, Field(description="Name of the Elasticsearch index containing the document")],
            doc_id: Annotated[str, Field(description="Document ID to retrieve from the index")]
    ) -> str:
        """Retrieve a specific document from Elasticsearch index."""
        try:
            es = get_es_client()
    
            result = es.get(index=index, id=doc_id)
    
            return f"✅ Document retrieved 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 get 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 "index_not_found_exception" in error_str or "no such index" in error_str:
                if "index" 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"💡 **Suggestions for agents**:\n"
                    error_message += f"   1. Use 'list_indices' tool to see all available indices\n"
                    error_message += f"   2. Check which indices contain your target data\n"
                    error_message += f"   3. Use the correct index name from the list\n"
                    error_message += f"   4. If no suitable index exists, create one with 'create_index' tool\n\n"
                else:
                    error_message += f"📄 **Document Not Found**: Document ID '{doc_id}' does not exist\n"
                    error_message += f"📍 The requested document was not found in index '{index}'\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
  • Mounts the elasticsearch_document sub-server into the unified Elasticsearch server app, registering the get_document tool (along with index_document and delete_document).
    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
  • Mounts the elasticsearch_server_app into the main FastMCP server, making get_document available at the top level.
    from src.elasticsearch.elasticsearch_server import app as elasticsearch_server_app  
    from src.prompts.prompt_server import app as prompt_server_app
    
    # Import middleware
    from src.middleware.confirmation_middleware import ConfirmationMiddleware
    
    # Load configuration and initialize components
    CONFIG = load_config()
    init_security(CONFIG["security"]["allowed_base_directory"])
    
    # Initialize confirmation manager
    confirmation_manager = initialize_confirmation_manager(CONFIG)
    print(f"✅ Confirmation system initialized (enabled: {CONFIG.get('confirmation', {}).get('enabled', True)})")
    
    # Auto-setup Elasticsearch if needed
    print("🔍 Checking Elasticsearch configuration...")
    config_path = Path(__file__).parent / "config.json"
    setup_result = auto_setup_elasticsearch(config_path, CONFIG)
    
    if setup_result["status"] == "setup_completed":
        # Reload config after setup
        CONFIG = load_config()
        print("✅ Elasticsearch auto-setup completed")
    elif setup_result["status"] == "already_configured":
        print("✅ Elasticsearch already configured")
    elif setup_result["status"] == "setup_failed":
        print(f"⚠️  Elasticsearch auto-setup failed: {setup_result.get('error', 'Unknown error')}")
        print("📝 You can manually setup using the 'setup_elasticsearch' tool")
    
    init_elasticsearch(CONFIG)
    
    # Create main FastMCP server
    app = FastMCP(
        name=CONFIG["server"]["name"],
        version=CONFIG["server"]["version"],
        instructions="🏗️ AgentKnowledgeMCP - Modern FastMCP server with modular composition architecture for knowledge management, Elasticsearch operations, file management, and system administration"
    )
    
    # ================================
    # MIDDLEWARE CONFIGURATION
    # ================================
    
    print("🔒 Adding confirmation middleware...")
    
    # Add confirmation middleware to main server
    app.add_middleware(ConfirmationMiddleware())
    
    print("✅ Confirmation middleware added successfully!")
    
    # ================================
    # SERVER COMPOSITION - MOUNTING
    # ================================
    
    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)
  • Input schema for get_document tool: requires 'index' (str) and 'doc_id' (str) parameters with descriptions.
    index: Annotated[str, Field(description="Name of the Elasticsearch index containing the document")],
    doc_id: Annotated[str, Field(description="Document ID to retrieve from the 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 but only states the basic operation. It doesn't disclose behavioral traits like error handling (e.g., if document doesn't exist), performance characteristics, authentication needs, or rate limits. For a read operation with zero annotation coverage, this is inadequate.

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?

Single sentence with zero waste - every word contributes to understanding the tool's purpose. Front-loaded with the core action and resource.

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 2 parameters with full schema coverage and an output schema exists, the description is minimally complete for purpose. However, as a read operation with no annotations, it should ideally mention what happens on failure (e.g., document not found) or return format 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%, so the schema already fully documents both parameters. The description adds no additional meaning beyond what the schema provides (e.g., no examples, format details, or constraints). Baseline 3 is appropriate when schema does all the work.

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 ('retrieve'), resource ('document from Elasticsearch index'), and method ('by document ID'). It distinguishes from siblings like search (which queries), list_indices (which lists indices), and delete_document (which removes).

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 usage when you need a specific document by ID, but doesn't explicitly state when to use alternatives like search (for queries) or list_indices (for index contents). No exclusions or prerequisites are mentioned.

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