Skip to main content
Glama
TMTrevisan

Unified Salesforce Documentation MCP Server

by TMTrevisan

search_local_docs

Search locally extracted Salesforce documentation in a SQLite database to find relevant sections based on your query.

Instructions

Search locally extracted Salesforce documentation in the SQLite database.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes
maxResultsNo

Implementation Reference

  • The handler for the 'search_local_docs' tool call. It parses the query/maxResults using SearchDocsSchema, calls searchDocuments() from db.ts, and formats results as markdown. Also handles edge cases (empty DB, no matches).
    if (name === "search_local_docs") {
        const { query, maxResults } = SearchDocsSchema.parse(args);
        const results = await searchDocuments(query, maxResults);
    
        if (results.length === 0) {
            const database = await getDatabase();
            const countStmt = database.prepare('SELECT COUNT(*) FROM documents');
            countStmt.step();
            const rowCount = countStmt.get()[0] as number;
            countStmt.free();
    
            if (rowCount === 0) {
                return {
                    content: [{
                        type: "text",
                        text: "No results found in the local database.\n\nNote: If this is a new installation, your local database is currently empty. You must run the `mass_extract_guide` tool on a Salesforce category URL first to index the documentation locally."
                    }]
                };
            } else {
                return {
                    content: [{
                        type: "text",
                        text: `No matching documentation found for "${query}". Try different or fewer keywords.`
                    }]
                };
            }
        }
    
        let output = `# Search Results for "${query}"\n\n`;
        for (const r of results) {
            output += `## [${r.title}](${r.url})\n*Category: ${r.category}* | *Score: ${(r.score * 100).toFixed(1)}%*\n\n`;
            output += `> ${r.matchContent.substring(0, 500)}...\n\n---\n`;
        }
    
        return { content: [{ type: "text", text: output }] };
    }
  • The searchDocuments() function performs the actual search in the SQLite database. It tokenizes the query, runs LIKE queries against chunked content, scores documents by term coverage and frequency, and returns the top results.
    export async function searchDocuments(query: string, maxResults: number = 5) {
        const database = await getDatabase();
        const queryLower = query.toLowerCase();
        const searchTerms = queryLower.split(/\s+/).filter(w => w.length > 2);
    
        if (searchTerms.length === 0) return [];
    
        const likeConditions = searchTerms.map(t => 'c.content_lower LIKE ?').join(' OR ');
        const params = searchTerms.map(t => `%${t}%`);
    
        const sql = `
            SELECT 
                d.id, d.url, d.title, d.category,
                c.content, c.content_lower
            FROM chunks c
            JOIN documents d ON c.document_id = d.id
            WHERE (${likeConditions})
            LIMIT 1000
        `;
    
        const stmt = database.prepare(sql);
        stmt.bind(params);
    
        const rows: any[] = [];
        const columns = stmt.getColumnNames();
        while (stmt.step()) {
            const rowData = stmt.get();
            const row: any = {};
            columns.forEach((col: string, idx: number) => row[col] = rowData[idx]);
            rows.push(row);
        }
        stmt.free();
    
        // BUG-10 Fix: Group matching chunks by document URL so we can score the document globally
        const docsByUrl = new Map();
        for (const row of rows) {
            if (!docsByUrl.has(row.url)) {
                docsByUrl.set(row.url, {
                    url: row.url,
                    title: row.title,
                    category: row.category,
                    chunks: []
                });
            }
            docsByUrl.get(row.url).chunks.push(row);
        }
    
        const scoredDocs = [];
        for (const doc of docsByUrl.values()) {
            let docHits = 0;
            let totalFreq = 0;
    
            // Evaluate each term against the combined content of all matched chunks for this doc
            const combinedLower = doc.chunks.map((c: any) => c.content_lower).join(' ');
    
            for (const term of searchTerms) {
                if (combinedLower.includes(term)) {
                    docHits++;
                    // Rough frequency count for tie-breaking
                    totalFreq += (combinedLower.split(term).length - 1);
                }
            }
    
            const density = docHits / searchTerms.length;
    
            // Find best individual chunk to use as the snippet
            let bestChunk = doc.chunks[0];
            let bestChunkHits = -1;
            for (const c of doc.chunks) {
                let cHits = 0;
                for (const term of searchTerms) {
                    if (c.content_lower.includes(term)) cHits++;
                }
                if (cHits > bestChunkHits) {
                    bestChunkHits = cHits;
                    bestChunk = c;
                }
            }
    
            scoredDocs.push({
                url: doc.url,
                title: doc.title,
                category: doc.category,
                matchContent: bestChunk.content,
                score: density,
                totalFreq
            });
        }
    
        // Sort by term coverage hits first, then by raw frequency
        scoredDocs.sort((a, b) => {
            if (b.score !== a.score) return b.score - a.score;
            return b.totalFreq - a.totalFreq;
        });
    
        return scoredDocs.slice(0, maxResults);
    }
  • The Zod schema 'SearchDocsSchema' used to validate inputs for the search_local_docs tool: query (string, 1-500 chars) and maxResults (number, 1-20, default 5).
    const SearchDocsSchema = z.object({
        query: z.string().min(1).max(500),
        maxResults: z.number().int().min(1).max(20).optional().default(5)
    });
  • src/index.ts:74-85 (registration)
    Registration of the 'search_local_docs' tool in the ListTools handler, including its name, description, and inputSchema (type, properties, required).
    {
        name: "search_local_docs",
        description: "Search locally extracted Salesforce documentation in the SQLite database.",
        inputSchema: {
            type: "object",
            properties: {
                query: { type: "string" },
                maxResults: { type: "number" }
            },
            required: ["query"]
        }
    },
Behavior2/5

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

No annotations are provided, and the description only states it searches without disclosing behavior like full-text search, exact match, pagination, or performance implications. The agent lacks information on what the tool actually does internally.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single sentence with no fluff. However, it is not front-loaded with the most critical information like parameter requirements or return type. Still, conciseness is adequate.

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

Completeness1/5

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

Given no output schema, no annotations, and only two parameters, the description is severely incomplete. It does not explain return values, result format, ranking, or edge cases, making it inadequate for an agent to use effectively.

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

Parameters1/5

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

Schema description coverage is 0%, and the description adds no meaning to the 'query' and 'maxResults' parameters. The agent only has the parameter names, which are insufficient for correct invocation.

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 verb 'Search' and the resource 'locally extracted Salesforce documentation in the SQLite database'. It distinguishes the tool from siblings like 'read_local_document' which implies reading a specific document.

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?

The description does not provide when to use this tool versus alternatives. No explicit context or exclusion is given. Siblings like 'mass_extract_guide' or 'read_local_document' are not referenced for differentiation.

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/TMTrevisan/unified-sf-docs-mcp'

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