Skip to main content
Glama

MCP Energy Server

by ebarros23
API_DOCUMENTATION.md11.2 kB
# 📡 MCP Energy Server - API Documentation Complete API reference for the MCP Energy web service. ## 🌐 Base URL Once deployed on Render.com: ``` https://your-service.onrender.com ``` For local testing: ``` http://localhost:10000 ``` ## 🔑 Authentication Currently, the API uses a pre-configured EIA API key. No authentication required for end users. ## 📋 Common Parameters All POST endpoints accept JSON with these common parameters: ```json { "frequency": "monthly", // "monthly", "quarterly", "annual", "weekly" "data_type": "generation", // Varies by endpoint "facets": { // Optional filters "stateid": ["CA", "TX"], "sectorid": ["RES"] } } ``` ## 🔌 Endpoints ### GET / - API Information Returns API metadata and available endpoints. **Request:** ```bash curl https://your-service.onrender.com/ ``` **Response:** ```json { "name": "MCP Energy Server", "version": "0.1.0", "description": "Energy Information Administration (EIA) data API", "endpoints": { "/electricity": "Electricity generation, consumption, sales, revenue", "/natural-gas": "Natural gas production, consumption, prices, storage", ... }, "docs": "/docs" } ``` --- ### GET /health - Health Check Monitoring endpoint that returns service status. **Request:** ```bash curl https://your-service.onrender.com/health ``` **Response:** ```json { "status": "healthy", "service": "mcp-energy" } ``` --- ### GET /docs - Interactive Documentation OpenAPI/Swagger UI for testing the API. **Access:** ``` https://your-service.onrender.com/docs ``` Opens an interactive interface where you can test all endpoints. --- ### POST /electricity - Electricity Data Get electricity generation, consumption, sales, or revenue data. **Parameters:** - `frequency`: "monthly", "quarterly", "annual" - `data_type`: "generation", "consumption", "sales", "revenue" - `facets`: Optional filters **Example Request:** ```bash curl -X POST https://your-service.onrender.com/electricity \ -H "Content-Type: application/json" \ -d '{ "frequency": "monthly", "data_type": "generation", "facets": { "stateid": ["CA"], "sectorid": ["ALL"] } }' ``` **Python Example:** ```python import requests response = requests.post( "https://your-service.onrender.com/electricity", json={ "frequency": "monthly", "data_type": "generation", "facets": {"stateid": ["CA"]} } ) data = response.json() print(data) ``` **JavaScript Example:** ```javascript fetch("https://your-service.onrender.com/electricity", { method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({ frequency: "monthly", data_type: "generation", facets: {stateid: ["CA"]} }) }) .then(res => res.json()) .then(data => console.log(data)); ``` --- ### POST /natural-gas - Natural Gas Data Get natural gas production, consumption, prices, or storage data. **Parameters:** - `frequency`: "monthly", "quarterly", "annual" - `data_type`: "production", "consumption", "prices", "storage" - `facets`: Optional filters **Example Request:** ```bash curl -X POST https://your-service.onrender.com/natural-gas \ -H "Content-Type: application/json" \ -d '{ "frequency": "monthly", "data_type": "consumption" }' ``` **Response Format:** ```json { "response": { "data": [ { "period": "2024-01", "value": 123.45, "units": "million cubic feet" } ] } } ``` --- ### POST /petroleum - Petroleum Data Get petroleum production, consumption, imports, exports, prices, or stocks. **Parameters:** - `frequency`: "weekly", "monthly", "quarterly", "annual" - `data_type`: "production", "consumption", "imports", "exports", "prices", "stocks" - `facets`: Optional filters **Example Request:** ```bash curl -X POST https://your-service.onrender.com/petroleum \ -H "Content-Type: application/json" \ -d '{ "frequency": "weekly", "data_type": "prices" }' ``` --- ### POST /coal - Coal Data Get coal production, consumption, or price data. **Parameters:** - `frequency`: "monthly", "quarterly", "annual" - `data_type`: "production", "consumption", "prices" - `facets`: Optional filters **Example Request:** ```bash curl -X POST https://your-service.onrender.com/coal \ -H "Content-Type: application/json" \ -d '{ "frequency": "quarterly", "data_type": "production" }' ``` --- ### POST /renewable - Renewable Energy Data Get renewable energy generation data (solar, wind, hydro, etc.). **Parameters:** - `frequency`: "monthly", "quarterly", "annual" - `facets`: Optional filters (can specify energy source) **Example Request:** ```bash curl -X POST https://your-service.onrender.com/renewable \ -H "Content-Type: application/json" \ -d '{ "frequency": "monthly", "facets": { "fuelid": ["SUN"] } }' ``` **Common Fuel IDs:** - `SUN` - Solar - `WND` - Wind - `HYC` - Hydro Conventional - `GEO` - Geothermal - `WAS` - Biomass --- ### POST /co2-emissions - CO2 Emissions Data Get CO2 emissions data by state and sector. **Parameters:** - `frequency`: "monthly", "annual" - `facets`: Optional filters **Example Request:** ```bash curl -X POST https://your-service.onrender.com/co2-emissions \ -H "Content-Type: application/json" \ -d '{ "frequency": "annual", "facets": { "stateid": ["US"] } }' ``` --- ### POST /steo - Short-Term Energy Outlook Get STEO forecast data. **Parameters:** - `frequency`: "monthly" (only) - `facets`: Optional filters **Example Request:** ```bash curl -X POST https://your-service.onrender.com/steo \ -H "Content-Type: application/json" \ -d '{ "frequency": "monthly" }' ``` --- ### POST /international - International Energy Data Get international energy statistics. **Parameters:** - `frequency`: "annual" - `facets`: Optional filters (can specify country) **Example Request:** ```bash curl -X POST https://your-service.onrender.com/international \ -H "Content-Type: application/json" \ -d '{ "frequency": "annual", "facets": { "countryRegionId": ["CAN"] } }' ``` --- ## 🎯 Complete Examples ### Get California Solar Generation ```python import requests url = "https://your-service.onrender.com/renewable" payload = { "frequency": "monthly", "facets": { "stateid": ["CA"], "fuelid": ["SUN"] } } response = requests.post(url, json=payload) data = response.json() # Process data for record in data['response']['data'][:10]: # First 10 records print(f"{record['period']}: {record['value']} {record['units']}") ``` ### Compare Natural Gas Prices ```python import requests url = "https://your-service.onrender.com/natural-gas" payload = { "frequency": "monthly", "data_type": "prices" } response = requests.post(url, json=payload) data = response.json() # Analyze price trends prices = [record['value'] for record in data['response']['data'][:12]] avg_price = sum(prices) / len(prices) print(f"Average price (last 12 months): ${avg_price:.2f}") ``` ### Fetch Multiple Data Types ```python import requests import asyncio import aiohttp async def fetch_data(session, endpoint, payload): url = f"https://your-service.onrender.com/{endpoint}" async with session.post(url, json=payload) as response: return await response.json() async def main(): async with aiohttp.ClientSession() as session: tasks = [ fetch_data(session, "electricity", {"frequency": "monthly"}), fetch_data(session, "natural-gas", {"frequency": "monthly"}), fetch_data(session, "petroleum", {"frequency": "monthly"}) ] results = await asyncio.gather(*tasks) return results # Run results = asyncio.run(main()) print(f"Fetched {len(results)} datasets") ``` --- ## 🔍 Facets (Filters) Common facet keys for filtering: ### State IDs ```json { "facets": { "stateid": ["CA", "TX", "NY", "FL"] } } ``` ### Sector IDs ```json { "facets": { "sectorid": ["RES", "COM", "IND", "TRA"] } } ``` - `RES` - Residential - `COM` - Commercial - `IND` - Industrial - `TRA` - Transportation ### Fuel IDs ```json { "facets": { "fuelid": ["SUN", "WND", "NG", "COL"] } } ``` --- ## ❌ Error Responses ### 500 Internal Server Error ```json { "detail": "Error message from EIA API" } ``` **Common causes:** - Invalid facet values - EIA API is down - Invalid API key ### 422 Validation Error ```json { "detail": [ { "loc": ["body", "frequency"], "msg": "field required", "type": "value_error.missing" } ] } ``` **Cause:** Invalid request payload --- ## 🚀 Rate Limiting - No rate limiting implemented on the MCP server side - EIA API has its own rate limits (check EIA documentation) - Free Render tier may have request limits **Best practices:** - Implement caching for frequently accessed data - Batch requests when possible - Monitor your usage --- ## 📊 Response Format All successful responses follow this general structure: ```json { "response": { "data": [ { "period": "2024-01", "value": 123.45, "units": "string", "stateid": "CA", "sectorid": "RES", // ... other fields vary by endpoint } ], "request": { "frequency": "monthly", // ... request parameters } } } ``` --- ## 🛠️ SDKs and Libraries ### Python ```bash pip install requests # or pip install httpx ``` ### JavaScript/Node.js ```bash npm install axios # or use native fetch ``` ### Example Wrapper Class (Python) ```python import requests class MCPEnergyClient: def __init__(self, base_url): self.base_url = base_url def get_electricity(self, frequency="monthly", data_type="generation", facets=None): return requests.post( f"{self.base_url}/electricity", json={ "frequency": frequency, "data_type": data_type, "facets": facets or {} } ).json() def get_natural_gas(self, frequency="monthly", data_type="consumption", facets=None): return requests.post( f"{self.base_url}/natural-gas", json={ "frequency": frequency, "data_type": data_type, "facets": facets or {} } ).json() # Add other methods... # Usage client = MCPEnergyClient("https://your-service.onrender.com") data = client.get_electricity(facets={"stateid": ["CA"]}) ``` --- ## 🔗 Resources - **Interactive Docs**: `https://your-service.onrender.com/docs` - **EIA API Docs**: https://www.eia.gov/opendata/ - **Render Docs**: https://render.com/docs --- ## 💡 Tips 1. **Use Interactive Docs**: Visit `/docs` to test endpoints in your browser 2. **Cache Results**: Store frequently accessed data to reduce API calls 3. **Batch Requests**: Fetch multiple datasets in parallel 4. **Monitor Usage**: Track your API usage on Render dashboard 5. **Handle Errors**: Always implement error handling in production --- **Your API is ready to serve energy data!** 🎉

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/ebarros23/mcp-energy'

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