Skip to main content
Glama
ispyridis

Calibre RAG MCP Server

by ispyridis

search_project_context

Find relevant context chunks within your Calibre ebook projects using semantic search to support research, writing, or content analysis.

Instructions

Search for relevant context chunks within a RAG project using vector similarity

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
project_nameYesName of the project to search
queryYesQuery to find relevant context
limitNoMaximum number of context chunks to return (default: 5)

Implementation Reference

  • Core handler function that loads vectors and metadata from the project, generates query embedding, computes cosine similarities, retrieves top matching chunks, and returns relevant context.
    async searchProjectContext(projectName, query, limit = CONFIG.RAG.MAX_CONTEXT_CHUNKS) {
        const project = this.projects.get(projectName);
        if (!project) {
            throw new Error(`Project '${projectName}' not found`);
        }
        
        const projectPath = path.join(CONFIG.RAG.PROJECTS_DIR, projectName);
        const vectorsPath = path.join(projectPath, 'vectors.bin');
        const metadataPath = path.join(projectPath, 'metadata.json');
        const chunksPath = path.join(projectPath, 'chunks');
        
        // Load vectors and metadata
        const { vectors } = this.loadVectors(vectorsPath);
        
        if (!fs.existsSync(metadataPath) || vectors.length === 0) {
            throw new Error(`No vector data found for project '${projectName}'`);
        }
        
        const metadata = JSON.parse(fs.readFileSync(metadataPath, 'utf8'));
        
        // Generate query embedding
        const queryEmbedding = await this.generateEmbedding(query);
        
        // Calculate similarities
        const similarities = vectors.map((vector, index) => ({
            index,
            similarity: this.cosineSimilarity(queryEmbedding, vector),
            metadata: metadata[index]
        }));
        
        // Sort by similarity and get top results
        similarities.sort((a, b) => b.similarity - a.similarity);
        const topResults = similarities.slice(0, limit);
        
        // Load chunk content
        const contextChunks = [];
        for (const result of topResults) {
            const chunkId = result.metadata.chunk_index !== undefined ? 
                `chunk_${result.metadata.chunk_index}` : `chunk_${result.index}`;
            const chunkPath = path.join(chunksPath, `${chunkId}.json`);
            
            if (fs.existsSync(chunkPath)) {
                const chunk = JSON.parse(fs.readFileSync(chunkPath, 'utf8'));
                contextChunks.push({
                    ...chunk,
                    similarity: result.similarity,
                    book_title: result.metadata.title,
                    authors: result.metadata.authors
                });
            }
        }
        
        return contextChunks;
    }
  • Tool schema definition including name, description, and input validation schema.
    {
        name: 'search_project_context',
        description: 'Search for relevant context chunks within a RAG project using vector similarity',
        inputSchema: {
            type: 'object',
            properties: {
                project_name: {
                    type: 'string',
                    description: 'Name of the project to search'
                },
                query: {
                    type: 'string',
                    description: 'Query to find relevant context'
                },
                limit: {
                    type: 'integer',
                    description: 'Maximum number of context chunks to return (default: 5)',
                    default: 5
                }
            },
            required: ['project_name', 'query']
        }
    },
  • server.js:1188-1205 (registration)
    Tool registration and dispatching logic in the MCP tools/call handler switch statement, which validates arguments and invokes the handler.
    case 'search_project_context':
        const searchProjName = args.project_name;
        const searchQuery = args.query;
        const searchLimit = args.limit || 5;
        
        if (!searchProjName || !searchQuery) {
            this.sendError(id, -32602, 'Missing required parameters: project_name, query');
            return;
        }
        
        try {
            const contextChunks = await this.searchProjectContext(searchProjName, searchQuery, searchLimit);
            const mcpResult = this.formatResponse(contextChunks, searchQuery, 'context');
            this.sendSuccess(id, mcpResult);
        } catch (error) {
            this.sendError(id, -32603, error.message);
        }
        break;
Behavior2/5

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

With no annotations, the description carries full burden but lacks behavioral details. It mentions 'vector similarity' as the search method but doesn't disclose expected outputs (e.g., format of context chunks), error conditions, permissions needed, or performance traits like rate limits. This is inadequate for a search tool with zero annotation coverage.

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 with zero waste—it directly states the tool's purpose and method. It's appropriately sized and front-loaded, making it easy to parse quickly.

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

Completeness2/5

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

Given no annotations, no output schema, and a search operation with behavioral unknowns, the description is incomplete. It doesn't explain what 'context chunks' are, their format, or how results are returned, leaving gaps for an agent to use the tool effectively in a RAG 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 fully documents parameters (project_name, query, limit). The description adds no additional meaning beyond implying 'query' is used for vector similarity search, which is already suggested by the schema. Baseline 3 is appropriate as the schema does the heavy lifting.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('search for relevant context chunks') and resource ('within a RAG project'), specifying vector similarity as the method. It distinguishes from 'search' (a generic sibling) by focusing on project context, but doesn't explicitly contrast with other siblings like 'get_project_info' or 'fetch'.

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?

No guidance is provided on when to use this tool versus alternatives like 'search' (generic), 'get_project_info' (project metadata), or 'fetch' (unclear purpose). The description implies usage for retrieving context chunks but offers no explicit when/when-not criteria or prerequisites.

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/ispyridis/calibre-rag-mcp-nodejs'

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