economicIndicators_cpi
Retrieve US Consumer Price Index (CPI) data in JSON or CSV format for monthly or semiannual intervals. Access economic indicators to analyze inflation trends and support financial decision-making.
Instructions
Retrieves US Consumer Price Index (CPI) data.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| datatype | No | Data format for the response. | json |
| interval | No | Time interval. | monthly |
Input Schema (JSON Schema)
{
"additionalProperties": false,
"description": "Parameters for fetching CPI data.",
"properties": {
"datatype": {
"default": "json",
"description": "Data format for the response.",
"enum": [
"json",
"csv"
],
"type": "string"
},
"interval": {
"default": "monthly",
"description": "Time interval.",
"enum": [
"monthly",
"semiannual"
],
"type": "string"
}
},
"type": "object"
}
Implementation Reference
- src/index.ts:615-626 (registration)Registers the 'economicIndicators_cpi' MCP tool with server.addTool. Specifies the tool name, description, input parameters schema from schemas.ts, and an inline execute function that delegates to the generic executeAvantageTool helper, ultimately calling the AVantage library's av.economicIndicators.cpi(params) method.server.addTool({ name: "economicIndicators_cpi", description: "Retrieves US Consumer Price Index (CPI) data.", parameters: schemas.EconomicIndicatorsCPIParamsSchema, execute: ( args, context // Let type be inferred ) => executeAvantageTool("economicIndicators_cpi", args, context, (av, params) => av.economicIndicators.cpi(params) ), });
- src/schemas.ts:139-142 (schema)Defines the Zod validation schema for the tool's input parameters: optional 'interval' (monthly or semiannual, defaults to monthly) and optional 'datatype' (json or csv, defaults to json).export const EconomicIndicatorsCPIParamsSchema = z.object({ interval: z.enum(['monthly', 'semiannual']).default('monthly').optional().describe('Time interval.'), datatype: DatatypeSchema.default('json').optional(), }).describe('Parameters for fetching CPI data.')
- src/index.ts:38-115 (helper)Generic helper function used by all tools, including economicIndicators_cpi, to manage authentication (API key resolution), create/reuse AVantage client instances via resourceManager, execute the provided avantageMethod (av.economicIndicators.cpi for this tool), handle errors, and return JSON-stringified data.async function executeAvantageTool<TArgs, TResult>( toolName: string, args: TArgs, context: Context<Record<string, unknown> | undefined>, // Use the imported Context type directly avantageMethod: ( av: AVantage, args: TArgs ) => Promise<{ error?: boolean; reason?: string; data?: TResult }> ): Promise<string> { logger.info(`Executing '${toolName}' tool for request ID: ${context}`); logger.debug(`Args for ${toolName}: ${JSON.stringify(args)}`); // --- Authentication & Resource Management --- // Access extraArgs safely - it might be null or undefined const extraArgsApiKey = context.extraArgs?.apiKey as string | undefined; const apiKey = extraArgsApiKey || config.apiKey; if (!apiKey) { logger.error(`'${toolName}' failed: Alpha Vantage API key missing.`); throw new UserError(apiKeyErrorMessage); } logger.debug( `Using AV API key (source: ${extraArgsApiKey ? "extraArgs" : "environment"}) for ${toolName}` ); try { // Get or create AVantage instance managed by ResourceManager const av = await resourceManager.getResource<AVantage>( apiKey, // Cache key is the resolved API key "avantage_client", // Type identifier for logging async (key) => { // Factory Function logger.info( `Creating new AVantage instance for key ending ...${key.slice(-4)}` ); // AVantage library reads AV_PREMIUM from process.env internally return new AVantage(key); }, async (avInstance) => { // Cleanup Function (no-op needed for AVantage) logger.debug(`Destroying AVantage instance (no-op)`); } ); // --- Library Call --- const result = await avantageMethod(av, args); // --- Response Handling --- if (result.error) { logger.warn( `'${toolName}' failed. Reason from avantage: ${result.reason}` ); throw new UserError(result.reason || `Tool '${toolName}' failed.`); } if (result.data === undefined || result.data === null) { logger.warn(`'${toolName}' completed successfully but returned no data.`); return "null"; // Return string "null" for empty data } logger.info(`'${toolName}' completed successfully.`); // Stringify the data part of the response return JSON.stringify(result.data); } catch (error: any) { logger.error( `Error during execution of '${toolName}': ${error.message}`, error ); // If it's already a UserError, rethrow it if (error instanceof UserError) { throw error; } // Otherwise, wrap it in a UserError throw new UserError( `An unexpected error occurred while executing tool '${toolName}': ${error.message}` ); } }