Skip to main content
Glama

query_knowledge

Search a knowledge index with natural language queries to retrieve the most relevant documents. Returns top-k results based on semantic similarity.

Instructions

Semantic search over a knowledge index. Returns the top-k most relevant documents for a natural language query.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
index_nameYes
queryYes
top_kNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • Registration of the 'query_knowledge' tool via the @mcp.tool decorator, with name, description, and input parameters (index_name, query, top_k). The handler function delegates to kn.query_index.
    @mcp.tool(
        name="query_knowledge",
        description=(
            "Semantic search over a knowledge index. "
            "Returns the top-k most relevant documents for a natural language query."
        ),
    )
    async def query_knowledge(
        index_name: str,
        query: str,
        top_k: int = 5,
    ) -> list[dict[str, Any]]:
        """
        Args:
            index_name: The index to search.
            query: Natural language search query.
            top_k: Number of results to return (default 5).
        """
        return await kn.query_index(
            index_name=index_name,
            query=query,
            top_k=top_k,
        )
  • The handler function 'query_knowledge' that executes the tool logic. It calls kn.query_index() with the user-provided index_name, query, and top_k, returning a list of ranked documents.
    async def query_knowledge(
        index_name: str,
        query: str,
        top_k: int = 5,
    ) -> list[dict[str, Any]]:
        """
        Args:
            index_name: The index to search.
            query: Natural language search query.
            top_k: Number of results to return (default 5).
        """
        return await kn.query_index(
            index_name=index_name,
            query=query,
            top_k=top_k,
        )
  • The core helper function 'query_index' that performs semantic search. It generates an embedding for the query via Ollama, computes cosine similarity against all documents in the index, and returns the top_k most relevant results with scores.
    async def query_index(
        index_name: str,
        query: str,
        top_k: int = 5,
    ) -> list[dict[str, Any]]:
        idx = _indexes.get(index_name)
        if idx is None:
            raise ValueError(f"Index '{index_name}' not found.")
        q_emb = await oc.embeddings(idx.embed_model, query)
        scored = sorted(
            idx.documents,
            key=lambda d: _cosine(q_emb, d.embedding),
            reverse=True,
        )
        return [
            {
                "id": d.id,
                "score": round(_cosine(q_emb, d.embedding), 4),
                "text": d.text,
                "metadata": d.metadata,
            }
            for d in scored[:top_k]
        ]
  • The '_cosine' helper function used to compute cosine similarity between two embedding vectors.
    def _cosine(a: list[float], b: list[float]) -> float:
        dot = sum(x * y for x, y in zip(a, b))
        mag_a = math.sqrt(sum(x * x for x in a))
        mag_b = math.sqrt(sum(x * x for x in b))
        if mag_a == 0 or mag_b == 0:
            return 0.0
        return dot / (mag_a * mag_b)
Behavior2/5

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

No annotations are provided, so the description must fully disclose behavior. It only mentions that it is a semantic search returning documents, but does not state whether it is read-only, idempotent, or any side effects. Lacks behavioral details.

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?

Two sentences, front-loaded with purpose. No wasted words. Efficient and to the point.

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 presence of an output schema, the description can focus on input and behavior. However, for a search tool with three parameters, it could provide more context on the nature of queries or index, but it is minimally adequate.

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

Parameters2/5

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

Input schema has no descriptions (0% coverage), so the description must compensate. It only implicitly explains 'top_k' via 'top-k', but does not clarify 'index_name' or 'query'. The description adds minimal value beyond the schema.

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?

Description clearly states the tool performs semantic search over a knowledge index and returns top-k relevant documents. It uses specific verb 'search' and resource 'knowledge index', and distinguishes from sibling tools like add_document, create_index, list_indexes which are for other operations.

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?

Description implies when to use (for semantic search) but does not provide explicit guidance on when not to use or mention alternatives among siblings. No exclusions or context for choosing this over chat or generate.

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/deadSwank001/Nexus-MCP'

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