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
| Name | Required | Description | Default |
|---|---|---|---|
| index_name | Yes | ||
| query | Yes | ||
| top_k | No |
Output Schema
| Name | Required | Description | Default |
|---|---|---|---|
| result | Yes |
Implementation Reference
- src/foundry_reverse/server.py:329-351 (registration)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, ) - src/foundry_reverse/server.py:336-351 (handler)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)