Skip to main content
Glama
henryhawke

Wolfram Alpha MCP Server

by henryhawke

wolfram_query_with_assumptions

Clarify ambiguous Wolfram Alpha queries by specifying assumptions to get precise computational results when multiple interpretations exist.

Instructions

Query Wolfram Alpha with specific assumptions when the initial query returns multiple interpretations. Use this when you need to clarify ambiguous queries.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
inputYesThe exact same input from the previous query
assumptionYesThe assumption value to use from the previous query result
maxcharsNoMaximum number of characters in the response (default: 6800)

Implementation Reference

  • The core implementation of the tool logic. This shared handler for both Wolfram tools executes the API call to Wolfram Alpha, incorporates the 'assumption' parameter (required for wolfram_query_with_assumptions), processes the response, extracts assumptions for future use, and formats the output.
    private async handleWolframQuery(params: WolframQueryParams) {
        if (!this.apiKey) {
            throw new McpError(
                ErrorCode.InvalidRequest,
                'Wolfram Alpha App ID not configured. Please set the WOLFRAM_ALPHA_APP_ID environment variable.'
            );
        }
    
        if (!params.input || params.input.trim().length === 0) {
            throw new McpError(
                ErrorCode.InvalidParams,
                'Input parameter is required and cannot be empty'
            );
        }
    
        try {
            const url = 'https://www.wolframalpha.com/api/v1/llm-api';
            const queryParams: Record<string, string | number> = {
                appid: this.apiKey,
                input: params.input.trim(),
            };
    
            // Add optional parameters if provided
            if (params.maxchars) queryParams.maxchars = params.maxchars;
            if (params.assumption) queryParams.assumption = params.assumption;
            if (params.units) queryParams.units = params.units;
            if (params.currency) queryParams.currency = params.currency;
            if (params.countrycode) queryParams.countrycode = params.countrycode;
            if (params.languagecode) queryParams.languagecode = params.languagecode;
            if (params.location) queryParams.location = params.location;
            if (params.timezone) queryParams.timezone = params.timezone;
            if (params.width) queryParams.width = params.width;
            if (params.maxwidth) queryParams.maxwidth = params.maxwidth;
            if (params.plotwidth) queryParams.plotwidth = params.plotwidth;
            if (params.scantimeout) queryParams.scantimeout = params.scantimeout;
            if (params.formattimeout) queryParams.formattimeout = params.formattimeout;
            if (params.parsetimeout) queryParams.parsetimeout = params.parsetimeout;
            if (params.totaltimeout) queryParams.totaltimeout = params.totaltimeout;
    
            const response = await axios.get(url, {
                params: queryParams,
                timeout: (params.totaltimeout || 30) * 1000, // Convert to milliseconds
                headers: {
                    'User-Agent': 'WolframAlpha-MCP-Server/1.0.0',
                },
            });
    
            if (response.status === 200) {
                const result = response.data;
    
                // Parse the response to extract useful information
                const lines = result.split('\n');
                let formattedResult = result;
    
                // Look for assumptions in the response
                const assumptions: string[] = [];
                let inAssumptions = false;
    
                for (const line of lines) {
                    if (line.includes('Assumptions:') || line.includes('Input interpretation:')) {
                        inAssumptions = true;
                    } else if (inAssumptions && line.trim() && !line.includes('Result:')) {
                        if (line.includes('|')) {
                            assumptions.push(line.trim());
                        }
                    } else if (line.includes('Result:')) {
                        inAssumptions = false;
                    }
                }
    
                let metadata = `**Query:** "${params.input}"\n\n`;
    
                if (assumptions.length > 0) {
                    metadata += `**Available Assumptions:**\n${assumptions.join('\n')}\n\n`;
                    metadata += `*If the result is not what you expected, you can use the wolfram_query_with_assumptions tool with one of the assumption values above.*\n\n`;
                }
    
                return {
                    content: [
                        {
                            type: 'text',
                            text: metadata + formattedResult,
                        },
                    ],
                };
            } else {
                throw new McpError(
                    ErrorCode.InternalError,
                    `Wolfram Alpha API returned status ${response.status}: ${response.statusText}`
                );
            }
        } catch (error) {
            if (axios.isAxiosError(error)) {
                if (error.response?.status === 501) {
                    const errorMessage = error.response.data || 'Input cannot be interpreted by Wolfram Alpha';
                    throw new McpError(
                        ErrorCode.InvalidParams,
                        `Wolfram Alpha could not interpret the input: "${params.input}". ${errorMessage}. Try rephrasing your query with simpler, more specific terms.`
                    );
                } else if (error.response?.status === 400) {
                    throw new McpError(
                        ErrorCode.InvalidParams,
                        'Invalid request parameters. Please check your input and try again.'
                    );
                } else if (error.response?.status === 403) {
                    const errorData = error.response.data || '';
                    if (errorData.includes('Invalid appid')) {
                        throw new McpError(
                            ErrorCode.InvalidRequest,
                            'Invalid Wolfram Alpha App ID. Please check your WOLFRAM_ALPHA_APP_ID environment variable.'
                        );
                    } else if (errorData.includes('Appid missing')) {
                        throw new McpError(
                            ErrorCode.InvalidRequest,
                            'Wolfram Alpha App ID is missing. Please set the WOLFRAM_ALPHA_APP_ID environment variable.'
                        );
                    } else {
                        throw new McpError(
                            ErrorCode.InvalidRequest,
                            'Authentication failed with Wolfram Alpha API.'
                        );
                    }
                } else if (error.code === 'ENOTFOUND' || error.code === 'ECONNREFUSED') {
                    throw new McpError(
                        ErrorCode.InternalError,
                        'Unable to connect to Wolfram Alpha API. Please check your internet connection.'
                    );
                } else if (error.code === 'ETIMEDOUT') {
                    throw new McpError(
                        ErrorCode.InternalError,
                        'Request to Wolfram Alpha API timed out. The query may be too complex or the service may be temporarily unavailable.'
                    );
                } else {
                    throw new McpError(
                        ErrorCode.InternalError,
                        `Network error: ${error.message}`
                    );
                }
            } else {
                throw new McpError(
                    ErrorCode.InternalError,
                    `Unexpected error: ${error instanceof Error ? error.message : 'Unknown error'}`
                );
            }
        }
    }
  • Input schema specific to the wolfram_query_with_assumptions tool, requiring both 'input' and 'assumption' parameters.
    inputSchema: {
        type: 'object',
        properties: {
            input: {
                type: 'string',
                description: 'The exact same input from the previous query',
            },
            assumption: {
                type: 'string',
                description: 'The assumption value to use from the previous query result',
            },
            maxchars: {
                type: 'number',
                description: 'Maximum number of characters in the response (default: 6800)',
                default: 6800,
            },
        },
        required: ['input', 'assumption'],
    },
  • src/index.ts:132-154 (registration)
    Registration of the 'wolfram_query_with_assumptions' tool in the ListTools response, including its name, description, and input schema.
    {
        name: 'wolfram_query_with_assumptions',
        description: 'Query Wolfram Alpha with specific assumptions when the initial query returns multiple interpretations. Use this when you need to clarify ambiguous queries.',
        inputSchema: {
            type: 'object',
            properties: {
                input: {
                    type: 'string',
                    description: 'The exact same input from the previous query',
                },
                assumption: {
                    type: 'string',
                    description: 'The assumption value to use from the previous query result',
                },
                maxchars: {
                    type: 'number',
                    description: 'Maximum number of characters in the response (default: 6800)',
                    default: 6800,
                },
            },
            required: ['input', 'assumption'],
        },
    },
  • Dispatch logic in the CallToolRequest handler that routes calls to 'wolfram_query_with_assumptions' to the shared handleWolframQuery function.
    if (name === 'wolfram_query' || name === 'wolfram_query_with_assumptions') {
        return await this.handleWolframQuery(args as unknown as WolframQueryParams);
  • TypeScript interface defining the parameters for Wolfram queries, including the optional 'assumption' used by this tool.
    interface WolframQueryParams {
        input: string;
        maxchars?: number;
        assumption?: string;
        units?: string;
        currency?: string;
        countrycode?: string;
        languagecode?: string;
        location?: string;
        timezone?: string;
        width?: number;
        maxwidth?: number;
        plotwidth?: number;
        scantimeout?: number;
        formattimeout?: number;
        parsetimeout?: number;
        totaltimeout?: number;
    }
Behavior3/5

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

No annotations are provided, so the description carries the full burden. It mentions the tool's behavior in handling ambiguous queries and using assumptions, but lacks details on rate limits, authentication needs, error handling, or response format. For a query tool with no annotation coverage, this leaves gaps in behavioral understanding, though it covers the core operational context.

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 highly concise and well-structured in two sentences, with the first stating the purpose and the second providing usage guidelines. Every sentence earns its place by adding critical information without redundancy, making it front-loaded and efficient.

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 moderate complexity (3 parameters, no output schema, no annotations), the description is adequate but incomplete. It covers purpose and usage well, but lacks details on behavioral aspects like response handling or error cases. Without annotations or output schema, more context on what to expect from the tool would enhance completeness, though it meets minimum viability.

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 all parameters thoroughly. The description does not add any parameter-specific details beyond what the schema provides (e.g., it doesn't explain the format of 'assumption' or examples). Baseline 3 is appropriate as the schema handles the heavy lifting, but no extra semantic value is added.

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 ('Query Wolfram Alpha with specific assumptions') and resource ('Wolfram Alpha'), and explicitly distinguishes it from its sibling tool by specifying it's for when 'the initial query returns multiple interpretations.' This provides clear differentiation and a specific use case.

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 usage guidelines: 'Use this when you need to clarify ambiguous queries' and specifies it's for when 'the initial query returns multiple interpretations.' This clearly indicates when to use this tool versus alternatives (like the sibling 'wolfram_query'), offering direct context for selection.

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/henryhawke/wolfram-llm-mcp'

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