Skip to main content
Glama
henryhawke

Wolfram Alpha MCP Server

by henryhawke

wolfram_query

Query Wolfram Alpha for computational, mathematical, scientific, and factual information using natural language. Get answers about chemistry, physics, geography, history, art, astronomy, and more.

Instructions

Query Wolfram Alpha for computational, mathematical, scientific, and factual information. Supports natural language queries about entities in chemistry, physics, geography, history, art, astronomy, mathematics, and more.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
inputYesThe natural language query to send to Wolfram Alpha. Convert complex questions to simplified keyword queries when possible (e.g., "how many people live in France" becomes "France population").
maxcharsNoMaximum number of characters in the response (default: 6800)
assumptionNoAssumption to use when Wolfram Alpha provides multiple interpretations of a query
unitsNoUnit system preference (e.g., "metric", "imperial")
currencyNoCurrency preference for financial calculations
countrycodeNoCountry code for localized results
languagecodeNoLanguage code for results (queries should still be in English)
locationNoLocation for location-specific queries
timezoneNoTimezone for time-related calculations
widthNoWidth for generated images
maxwidthNoMaximum width for generated images
plotwidthNoWidth for plots and graphs
scantimeoutNoTimeout for scanning operations (seconds)
formattimeoutNoTimeout for formatting operations (seconds)
parsetimeoutNoTimeout for parsing operations (seconds)
totaltimeoutNoTotal timeout for the request (seconds)

Implementation Reference

  • The core handler function that executes the tool logic: validates params, calls Wolfram Alpha API via axios, processes response including assumptions, handles various errors, and returns formatted text content.
    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'}`
                );
            }
        }
    }
  • src/index.ts:57-131 (registration)
    Registration of the 'wolfram_query' tool in the ListToolsRequest handler, including name, description, and detailed inputSchema.
    {
        name: 'wolfram_query',
        description: 'Query Wolfram Alpha for computational, mathematical, scientific, and factual information. Supports natural language queries about entities in chemistry, physics, geography, history, art, astronomy, mathematics, and more.',
        inputSchema: {
            type: 'object',
            properties: {
                input: {
                    type: 'string',
                    description: 'The natural language query to send to Wolfram Alpha. Convert complex questions to simplified keyword queries when possible (e.g., "how many people live in France" becomes "France population").',
                },
                maxchars: {
                    type: 'number',
                    description: 'Maximum number of characters in the response (default: 6800)',
                    default: 6800,
                },
                assumption: {
                    type: 'string',
                    description: 'Assumption to use when Wolfram Alpha provides multiple interpretations of a query',
                },
                units: {
                    type: 'string',
                    description: 'Unit system preference (e.g., "metric", "imperial")',
                },
                currency: {
                    type: 'string',
                    description: 'Currency preference for financial calculations',
                },
                countrycode: {
                    type: 'string',
                    description: 'Country code for localized results',
                },
                languagecode: {
                    type: 'string',
                    description: 'Language code for results (queries should still be in English)',
                },
                location: {
                    type: 'string',
                    description: 'Location for location-specific queries',
                },
                timezone: {
                    type: 'string',
                    description: 'Timezone for time-related calculations',
                },
                width: {
                    type: 'number',
                    description: 'Width for generated images',
                },
                maxwidth: {
                    type: 'number',
                    description: 'Maximum width for generated images',
                },
                plotwidth: {
                    type: 'number',
                    description: 'Width for plots and graphs',
                },
                scantimeout: {
                    type: 'number',
                    description: 'Timeout for scanning operations (seconds)',
                },
                formattimeout: {
                    type: 'number',
                    description: 'Timeout for formatting operations (seconds)',
                },
                parsetimeout: {
                    type: 'number',
                    description: 'Timeout for parsing operations (seconds)',
                },
                totaltimeout: {
                    type: 'number',
                    description: 'Total timeout for the request (seconds)',
                },
            },
            required: ['input'],
        },
    },
  • TypeScript interface defining the input parameters for the Wolfram query tools, used for type checking in the handler.
    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;
    }
  • src/index.ts:163-170 (registration)
    Dispatch logic in the CallToolRequest handler that maps the 'wolfram_query' tool call to the handleWolframQuery function.
    if (name === 'wolfram_query' || name === 'wolfram_query_with_assumptions') {
        return await this.handleWolframQuery(args as unknown as WolframQueryParams);
    } else {
        throw new McpError(
            ErrorCode.MethodNotFound,
            `Unknown tool: ${name}`
        );
    }
Behavior2/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 that the tool queries Wolfram Alpha and supports natural language queries, but does not disclose behavioral traits such as rate limits, authentication needs, error handling, or response formats. This is a significant gap for a tool with 16 parameters and no output schema.

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 appropriately sized and front-loaded, starting with the core purpose and then listing supported domains. It uses two sentences efficiently without waste, though it could be slightly more structured by separating usage tips from the purpose statement.

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 the complexity (16 parameters, no annotations, no output schema), the description is incomplete. It lacks details on behavioral aspects, response handling, and error cases, which are crucial for a tool with many optional parameters and no structured output documentation. This leaves significant gaps for an AI agent.

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 16 parameters thoroughly. The description adds no additional parameter semantics beyond what the schema provides, such as examples or usage tips for the parameters. Baseline 3 is appropriate when the schema does the heavy lifting.

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') and resources ('computational, mathematical, scientific, and factual information'), and distinguishes it from its sibling by specifying the types of queries supported. It explicitly lists domains like chemistry, physics, geography, etc., making the scope unambiguous.

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

Usage Guidelines3/5

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

The description implies usage for computational and factual queries across various domains, but does not explicitly state when to use this tool versus its sibling 'wolfram_query_with_assumptions' or other alternatives. It provides context on supported query types but lacks explicit guidance on exclusions or comparisons.

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