Skip to main content
Glama

save_answer_query_direct

Process natural language queries using internal Vertex AI model knowledge, save responses to specified files for structured data retention and future reference.

Instructions

Answers a natural language query using only the internal knowledge of the configured Vertex AI model (gemini-2.5-pro-exp-03-25), does not use web search, and saves the answer to a file. Requires 'query' and 'output_path'.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
output_pathYesThe relative path where the generated answer should be saved.
queryYesThe natural language question to answer using only the model's internal knowledge.

Implementation Reference

  • Main execution handler for the save_answer_query_direct tool. Parses input args, builds prompt using the tool definition, calls the Vertex AI model to generate the answer, validates and creates directory if needed, writes the generated content to the specified output_path file, and returns success message.
    } else if (toolName === "save_answer_query_direct") {
        const parsedArgs = SaveAnswerQueryDirectArgsSchema.parse(args);
        const { output_path } = parsedArgs;
    
        const config = getAIConfig();
        const { systemInstructionText, userQueryText, useWebSearch, enableFunctionCalling } = toolDefinition.buildPrompt(args, config.modelId);
    
        const initialContents = buildInitialContent(systemInstructionText, userQueryText) as CombinedContent[];
        const toolsForApi = getToolsForApi(enableFunctionCalling, useWebSearch);
    
        const generatedContent = await callGenerativeAI(
            initialContents,
            toolsForApi
        );
    
        const validOutputPath = validateWorkspacePath(output_path);
        await fs.mkdir(path.dirname(validOutputPath), { recursive: true });
        await fs.writeFile(validOutputPath, generatedContent, "utf-8");
    
        return {
            content: [{ type: "text", text: `Successfully generated direct answer and saved to ${output_path}` }],
        };
  • Zod schema defining the required input parameters for the tool: 'query' (string) and 'output_path' (string). Used for validation in both tool definition and handler.
    export const SaveAnswerQueryDirectArgsSchema = z.object({
        query: z.string().describe("The natural language question to answer using only the model's internal knowledge."),
        output_path: z.string().describe("The relative path where the generated answer should be saved.")
    });
  • ToolDefinition export including name, description, inputSchema, and buildPrompt function. The buildPrompt constructs a comprehensive system prompt emphasizing internal knowledge only, structured reasoning, and formatting, then returns prompt components for the handler to use with the AI model.
    export const saveAnswerQueryDirectTool: ToolDefinition = {
        name: "save_answer_query_direct",
        description: `Answers a natural language query using only the internal knowledge of the configured Vertex AI model (${modelIdPlaceholder}), does not use web search, and saves the answer to a file. Requires 'query' and 'output_path'.`,
        inputSchema: SaveAnswerQueryDirectJsonSchema as any,
        buildPrompt: (args: any, modelId: string) => {
            const parsed = SaveAnswerQueryDirectArgsSchema.safeParse(args);
            if (!parsed.success) {
                throw new McpError(ErrorCode.InvalidParams, `Invalid arguments for save_answer_query_direct: ${parsed.error.errors.map(e => `${e.path.join('.')}: ${e.message}`).join(', ')}`);
            }
            const { query } = parsed.data; // output_path used in handler
    
            // --- Use Prompt Logic from answer_query_direct.ts ---
            const base = `You are an AI assistant specialized in answering questions with exceptional accuracy, clarity, and depth using your internal knowledge. You are an EXPERT at nuanced reasoning, knowledge organization, and comprehensive response creation, with particular strengths in explaining complex topics clearly and communicating knowledge boundaries honestly.`;
    
            const knowledge = ` KNOWLEDGE REPRESENTATION AND BOUNDARIES:
    1. Base your answer EXCLUSIVELY on your internal knowledge relevant to "${query}".
    2. Represent knowledge with appropriate nuance - distinguish between established facts, theoretical understanding, and areas of ongoing research or debate.
    3. When answering questions about complex or evolving topics, represent multiple perspectives, schools of thought, or competing theories.
    4. For historical topics, distinguish between primary historical events and later interpretations or historiographical debates.
    5. For scientific topics, distinguish between widely accepted theories, emerging hypotheses, and speculative areas at the frontier of research.
    6. For topics involving statistics or quantitative data, explicitly note that your information may not represent the most current figures.
    7. For topics involving current events, technological developments, or other time-sensitive matters, explicitly state that your knowledge has temporal limitations.
    8. For interdisciplinary questions, synthesize knowledge across domains while noting where disciplinary boundaries create different perspectives.`;
    
            const reasoning = ` REASONING METHODOLOGY:
    1. For analytical questions, employ structured reasoning processes: identify relevant principles, apply accepted methods, evaluate alternatives systematically.
    2. For questions requiring evaluation, establish clear criteria before making assessments, explaining their relevance and application.
    3. For causal explanations, distinguish between correlation and causation, noting multiple causal factors where relevant.
    4. For predictive questions, base forecasts only on well-established patterns, noting contingencies and limitations.
    5. For counterfactual or hypothetical queries, reason from established principles while explicitly noting the speculative nature.
    6. For questions involving uncertainty, use probabilistic reasoning rather than false certainty.
    7. For questions with ethical dimensions, clarify relevant frameworks and principles before application.
    8. For multi-part questions, apply consistent reasoning frameworks across all components.`;
    
            const structure = ` COMPREHENSIVE RESPONSE STRUCTURE:
    1. Begin with a direct, concise answer to the main query (2-4 sentences), providing the core information.
    2. Follow with a structured, comprehensive exploration that unpacks all relevant aspects of the topic.
    3. For complex topics, organize information hierarchically with clear headings and subheadings.
    4. Sequence information logically: conceptual foundations before applications, chronological ordering for historical developments, general principles before specific examples.
    5. For multi-faceted questions, address each dimension separately while showing interconnections.
    6. Where appropriate, include "Key Concepts" sections to define essential terminology or foundational ideas.
    7. For topics with practical applications, separate theoretical explanations from applied guidance.
    8. End with a "Knowledge Limitations" section that explicitly notes temporal boundaries, areas of uncertainty, or aspects requiring specialized expertise beyond your knowledge.`;
    
            const clarity = ` CLARITY AND PRECISION REQUIREMENTS:
    1. Use precise, domain-appropriate terminology while defining specialized terms on first use.
    2. Present quantitative information with appropriate precision, units, and contextual comparisons.
    3. Use conditional language ("typically," "generally," "often") rather than universal assertions when variance exists.
    4. For complex concepts, provide both technical explanations and accessible analogies or examples.
    5. When explaining processes or systems, identify both components and their relationships/interactions.
    6. For abstract concepts, provide concrete examples that demonstrate application.
    7. Distinguish clearly between descriptive statements (what is) and normative statements (what ought to be).
    8. Use consistent terminology throughout your answer, avoiding synonyms that might introduce ambiguity.`;
    
            const uncertainty = ` HANDLING UNCERTAIN KNOWLEDGE:
    1. Explicitly acknowledge when your knowledge is incomplete or uncertain on a specific aspect of the query.
    2. If you lack sufficient domain knowledge to provide a reliable answer, clearly state this limitation.
    3. When a question implies a factual premise that is incorrect, address the misconception before proceeding.
    4. For rapidly evolving fields, explicitly note that current understanding may have advanced beyond your knowledge.
    5. When multiple valid interpretations of a question exist, identify the ambiguity and address major interpretations.
    6. If a question touches on areas where consensus is lacking, present major competing viewpoints.
    7. For questions requiring very specific or specialized expertise (e.g., medical, legal, financial advice), note the limitations of general knowledge.
    8. NEVER fabricate information to fill gaps in your knowledge - honesty about limitations is essential.`;
    
            const format = ` FORMAT AND VISUAL STRUCTURE:
    1. Use clear, structured Markdown formatting to enhance readability and information hierarchy.
    2. Apply ## for major sections and ### for subsections.
    3. Use **bold** for key terms and emphasis.
    4. Use *italics* for definitions or secondary emphasis.
    5. Format code, commands, or technical syntax using \`code blocks\` with appropriate language specification.
    6. Create comparative tables for any topic with 3+ items that can be evaluated along common dimensions.
    7. Use numbered lists for sequential processes, ranked items, or any ordered information.
    8. Use bulleted lists for unordered collections of facts, options, or characteristics.
    9. For complex processes or relationships, create ASCII/text diagrams where beneficial.
    10. For statistical information, consider ASCII charts or described visualizations when they add clarity.`;
    
            const advanced = ` ADVANCED QUERY HANDLING:
    1. For ambiguous queries, acknowledge the ambiguity and provide a structured response addressing each reasonable interpretation.
    2. For multi-part queries, ensure comprehensive coverage of all components while maintaining a coherent overall structure.
    3. For queries that make incorrect assumptions, address the misconception directly before providing a corrected response.
    4. For iterative or follow-up queries, maintain consistency with previous answers while expanding the knowledge scope.
    5. For "how to" queries, provide detailed step-by-step instructions with explanations of principles and potential variations.
    6. For comparative queries, establish clear comparison criteria and evaluate each item consistently across dimensions.
    7. For questions seeking opinions or subjective judgments, provide a balanced overview of perspectives rather than a singular "opinion."
    8. For definitional queries, provide both concise definitions and expanded explanations with examples and context.`;
    
            const systemInstructionText = base + knowledge + reasoning + structure + clarity + uncertainty + format + advanced;
            const userQueryText = `I need a comprehensive answer to this question: "${query}"
    
    Please provide your COMPLETE response addressing all aspects of my question. Use your internal knowledge to give the most accurate, nuanced, and thorough answer possible. If your knowledge has limitations on this topic, please explicitly note those limitations rather than speculating.`;
    
            return {
                systemInstructionText: systemInstructionText,
                userQueryText: userQueryText,
                useWebSearch: false, // Hardcoded to false
                enableFunctionCalling: false
            };
        }
    };
  • Registration of the tool: imported as saveAnswerQueryDirectTool and included in the allTools array, which is exported and used by src/index.ts via toolMap for tool lookup and list_tools.
    import { saveAnswerQueryDirectTool } from "./save_answer_query_direct.js";
    import { saveAnswerQueryWebsearchTool } from "./save_answer_query_websearch.js";
    
    // Import new research-oriented tools
    import { codeAnalysisWithDocsTool } from "./code_analysis_with_docs.js";
    import { technicalComparisonTool } from "./technical_comparison.js";
    import { architecturePatternRecommendationTool } from "./architecture_pattern_recommendation.js";
    import { dependencyVulnerabilityScanTool } from "./dependency_vulnerability_scan.js";
    import { databaseSchemaAnalyzerTool } from "./database_schema_analyzer.js";
    import { securityBestPracticesAdvisorTool } from "./security_best_practices_advisor.js";
    import { testingStrategyGeneratorTool } from "./testing_strategy_generator.js";
    import { regulatoryComplianceAdvisorTool } from "./regulatory_compliance_advisor.js";
    import { microserviceDesignAssistantTool } from "./microservice_design_assistant.js";
    import { documentationGeneratorTool } from "./documentation_generator.js";
    
    
    export const allTools: ToolDefinition[] = [
        // Query & Generation Tools
        answerQueryWebsearchTool,
        answerQueryDirectTool,
        explainTopicWithDocsTool,
        getDocSnippetsTool,
        generateProjectGuidelinesTool,
        // Filesystem Tools
        readFileTool, // Handles single and multiple files now
        // readMultipleFilesTool, // Merged into readFileTool
        writeFileTool,
        editFileTool,
        // createDirectoryTool, // Removed
        listDirectoryTool,
        directoryTreeTool,
        moveFileTool,
        searchFilesTool,
        getFileInfoTool,
        executeTerminalCommandTool, // Renamed
        // Add the new combined tools
        saveGenerateProjectGuidelinesTool,
        saveDocSnippetTool,
        saveTopicExplanationTool,
        // Removed old save_query_answer, added new specific ones
        saveAnswerQueryDirectTool,
Behavior3/5

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

With no annotations provided, the description carries the full burden. It discloses key behavioral traits: the tool answers queries using only the model's internal knowledge (no web search) and saves to a file. However, it lacks details on error handling, file format, permissions needed, or rate limits, which are important for a write operation.

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 front-loaded and concise, with two sentences that efficiently convey purpose, constraints, and requirements. Every word earns its place, avoiding redundancy. The structure is clear: what it does, how it differs, and what it needs.

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 tool's complexity (a write operation with no annotations and no output schema), the description is moderately complete. It covers the core functionality and constraints but lacks details on behavioral aspects like error cases or output format. For a tool that saves files, more context on file handling would be beneficial.

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 documents both parameters ('query' and 'output_path') adequately. The description adds minimal value by reinforcing that 'query' is natural language and 'output_path' is for saving, but doesn't provide additional syntax or format details beyond the schema. Baseline 3 is appropriate.

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 tool's purpose with specific verbs ('answers', 'saves') and resources ('natural language query', 'file'), distinguishing it from siblings like 'answer_query_direct' (which doesn't save) and 'save_answer_query_websearch' (which uses web search). It explicitly mentions using only the model's internal knowledge, which is a key differentiator.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides explicit guidance on when to use this tool: for answering queries with the model's internal knowledge and saving to a file. It implicitly contrasts with 'answer_query_websearch' (which uses web search) and 'answer_query_direct' (which doesn't save), making alternatives clear. The 'Requires' statement sets 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

Related 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/shariqriazz/vertex-ai-mcp-server'

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