Skip to main content
Glama
wn01011

llm-token-tracker

get_exchange_rate

Retrieve current USD to KRW exchange rates with optional cache refresh for accurate currency conversion tracking.

Instructions

Get current USD to KRW exchange rate with cache info

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
force_refreshNoForce refresh from API (default: false)

Implementation Reference

  • Registration of the 'get_exchange_rate' tool in the ListToolsRequestSchema handler, including name, description, and input schema.
    {
      name: 'get_exchange_rate',
      description: 'Get current USD to KRW exchange rate with cache info',
      inputSchema: {
        type: 'object',
        properties: {
          force_refresh: {
            type: 'boolean',
            description: 'Force refresh from API (default: false)',
            default: false
          }
        }
      }
    }
  • Primary MCP tool handler for 'get_exchange_rate' that delegates to tracker and formats the user-friendly response.
    private async getExchangeRate(args: any) {
      const { force_refresh = false } = args;
      
      try {
        let rate: number;
        let info: any;
        
        if (force_refresh) {
          rate = await this.tracker.refreshExchangeRate();
          info = await this.tracker.getExchangeRateInfo();
        } else {
          info = await this.tracker.getExchangeRateInfo();
          rate = info.rate;
        }
        
        const lastUpdated = info.lastUpdated 
          ? new Date(info.lastUpdated).toLocaleString()
          : 'Never';
        
        const timeSinceUpdate = info.lastUpdated
          ? Math.round((Date.now() - new Date(info.lastUpdated).getTime()) / (1000 * 60 * 60))
          : null;
        
        let result = `💱 Exchange Rate (USD to KRW)\n`;
        result += `━━━━━━━━━━━━━━━━━━━━━━\n`;
        result += `💵 Current Rate: ₩${rate.toFixed(2)}\n`;
        result += `📅 Last Updated: ${lastUpdated}\n`;
        
        if (timeSinceUpdate !== null) {
          result += `⏰ ${timeSinceUpdate} hours ago\n`;
        }
        
        result += `🔄 Source: ${info.source || 'fallback'}\n`;
        result += `━━━━━━━━━━━━━━━━━━━━━━\n\n`;
        result += `💡 Rate updates automatically every 24 hours\n`;
        result += `   Cache location: ~/.llm-token-tracker/exchange-rate.json`;
        
        return {
          content: [{ type: 'text', text: result }]
        };
      } catch (error) {
        return {
          content: [
            {
              type: 'text',
              text: `❌ Failed to get exchange rate: ${error instanceof Error ? error.message : 'Unknown error'}`
            }
          ]
        };
      }
    }
  • Helper method in TokenTracker that retrieves current exchange rate and cache info from ExchangeRateManager.
    async getExchangeRateInfo(): Promise<{
      rate: number;
      lastUpdated: string | null;
      source: string | null;
    }> {
      const cached = this.exchangeRateManager.getCacheInfo();
      const currentRate = await this.exchangeRateManager.getUSDtoKRW();
      
      return {
        rate: currentRate,
        lastUpdated: cached?.lastUpdated || null,
        source: cached?.source || null
      };
    }
  • Core ExchangeRateManager method that gets USD->KRW rate from cache, API, or fallback.
    async getUSDtoKRW(): Promise<number> {
      // Try to get from cache first
      const cached = this.loadFromCache();
      if (cached && !this.isCacheExpired(cached.lastUpdated)) {
        return cached.rate;
      }
    
      // Fetch fresh rate
      try {
        const rate = await this.fetchExchangeRate();
        this.saveToCache(rate, 'exchangerate-api');
        return rate;
      } catch (error) {
        console.error('Failed to fetch exchange rate:', error);
        
        // Use cached rate even if expired
        if (cached) {
          console.log('Using expired cache due to API failure');
          return cached.rate;
        }
        
        // Fall back to default rate
        console.log(`Using fallback rate: ${this.fallbackRate}`);
        return this.fallbackRate;
      }
    }
  • Private method that fetches fresh exchange rate from exchangerate-api.com API.
    private async fetchExchangeRate(): Promise<number> {
      // Using exchangerate-api.com (free tier, no API key required)
      const url = 'https://api.exchangerate-api.com/v4/latest/USD';
      
      const response = await fetch(url);
      
      if (!response.ok) {
        throw new Error(`API request failed: ${response.status}`);
      }
      
      const data: any = await response.json();
      
      if (!data.rates || !data.rates.KRW) {
        throw new Error('Invalid API response format');
      }
      
      return data.rates.KRW as 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 'cache info', which hints at caching behavior, but doesn't disclose details like cache duration, refresh mechanisms, or rate limits. It implies a read operation but doesn't specify error conditions or authentication needs. The description adds some context but lacks comprehensive behavioral details.

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 a single, efficient sentence that front-loads the core purpose ('Get current USD to KRW exchange rate') and adds a key feature ('with cache info') without unnecessary words. It's appropriately sized for a simple tool with one parameter.

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 low complexity (one optional parameter, no output schema, no annotations), the description is minimally adequate. It covers the basic purpose and hints at caching behavior, but lacks details on return values, error handling, or integration context. For a financial data tool, more completeness would be beneficial, but it meets the minimum for this context.

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?

The input schema has 100% description coverage, with one parameter ('force_refresh') fully documented in the schema. The description doesn't add any parameter-specific information beyond what the schema provides, such as explaining when to use 'force_refresh' or its impact on caching. With high schema coverage, the baseline is 3.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's function: 'Get current USD to KRW exchange rate with cache info'. It specifies the verb ('Get'), resource ('USD to KRW exchange rate'), and an additional feature ('cache info'). However, it doesn't explicitly differentiate from sibling tools, which appear unrelated (usage tracking, session management, cost comparison).

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 provides no guidance on when to use this tool versus alternatives. It doesn't mention any prerequisites, constraints, or scenarios where this tool is preferred over other methods. The sibling tools seem unrelated, but no explicit comparison or exclusion criteria are provided.

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/wn01011/llm-token-tracker'

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