Home / Articles

Practical notes: Build an AI Financial Agent with EODHD’s MCP Server

Operable walkthrough of Practical notes: Build an AI Financial Agent with EODHD’s MCP Server: contracts, checks, and drop-in code slots for teams shipping mcp systems without.

Publisher: REACTAPP.TOP12 min read2864 words

This article is published in English.

Sources: Build an AI Financial Agent with EODHD’s MCP Server

This walkthrough rebuilds the path from raw materials to a working system for: Build an AI Financial Agent with EODHD’s MCP Server. The focus is operable steps, explicit checks, and code that you can drop into a repo without guessing intent. For Overview, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Treat this stage as a contract between inputs and validated outputs. Name the artifacts, define success checks, and refuse silent partial completion.

The Traditional Financial Data API Approach Breaks Down Fast

When working through The Traditional Financial Data API Approach Breaks Down Fast, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Record timings and token or query cost next to functional results. Cost visibility early prevents surprise bills when the path moves from demo to shared environments. Log tool name, args hash, latency, and outcome for every call. Debugging agent loops without that trail wastes hours.

The Real Problem Is Context, Not Data

When working through The Real Problem Is Context, Not Data, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Keep configuration outside application code. Environment files, secret stores, and feature flags belong in one place operators can audit without reading the whole graph. Log tool name, args hash, latency, and outcome for every call. Debugging agent loops without that trail wastes hours.

What an MCP Server Changes for Financial Data APIs

When working through What an MCP Server Changes for Financial Data APIs, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Document the happy path and the recovery path together. Retries, human gates, and dead-letter handling are part of the product, not later polish. Log tool name, args hash, latency, and outcome for every call. Debugging agent loops without that trail wastes hours. When working through What an MCP Server Changes for Financial Data APIs, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Treat this stage as a contract between inputs and validated outputs. Name the artifacts, define success checks, and refuse silent partial completion.

Building the AI Financial Agent with EODHD’s MCP Server

Building the AI Financial Agent with EODHD’s MCP Server works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Record timings and token or query cost next to functional results. Cost visibility early prevents surprise bills when the path moves from demo to shared environments. Expose tools with narrow schemas and explicit side-effect labels. Hosts need to know which calls mutate state before they auto-approve.

Setup

Setup works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Keep configuration outside application code. Environment files, secret stores, and feature flags belong in one place operators can audit without reading the whole graph. Expose tools with narrow schemas and explicit side-effect labels. Hosts need to know which calls mutate state before they auto-approve.

pip install anthropic

Connecting the agent to EODHD’s MCP server in Python

Connecting the agent to EODHD’s MCP server in Python works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Document the happy path and the recovery path together. Retries, human gates, and dead-letter handling are part of the product, not later polish. Pin the interpreter and dependency lockfile before teaching the loop. Drift between laptop and CI is the most common silent break for API demos. Connecting the agent to EODHD’s MCP server in Python works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Treat this stage as a contract between inputs and validated outputs. Name the artifacts, define success checks, and refuse silent partial completion.

import anthropic
client = anthropic.Anthropic(api_key="YOUR_ANTHROPIC_API_KEY")EODHD_API_KEY = "YOUR_EODHD_API_TOKEN"response = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1500,
    messages=[
        {
            "role": "user",
            "content": (
                "Give me a quick pre-earnings health check on AAPL: "
                "key fundamentals, the next earnings date, and how the "
                "stock has moved over the last month."
            )
        }
    ],
    mcp_servers=[
        {
            "type": "url",
            "url": f"https://mcp.eodhd.com/v1/mcp?apikey={EODHD_API_KEY}",
            "name": "eodhd-mcp"
        }
    ]
)for block in response.content:
    if block.type == "text":
        print(block.text)

What’s actually happening here

For What’s actually happening here, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Record timings and token or query cost next to functional results. Cost visibility early prevents surprise bills when the path moves from demo to shared environments. Authenticate at the gateway and re-authorize at the data plane. A bearer token alone is not a tenancy boundary.

Reading the response

For Reading the response, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Keep configuration outside application code. Environment files, secret stores, and feature flags belong in one place operators can audit without reading the whole graph. Authenticate at the gateway and re-authorize at the data plane. A bearer token alone is not a tenancy boundary.

tool_calls = [
    {"name": b.name, "input": b.input}
    for b in response.content
    if b.type == "mcp_tool_use"
]
for call in tool_calls:
    print(call["name"], call["input"])

Scoring Stock Opportunities with EODHD’s Financial Data API

For Scoring Stock Opportunities with EODHD’s Financial Data API, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Document the happy path and the recovery path together. Retries, human gates, and dead-letter handling are part of the product, not later polish. Authenticate at the gateway and re-authorize at the data plane. A bearer token alone is not a tenancy boundary. For Scoring Stock Opportunities with EODHD’s Financial Data API, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Treat this stage as a contract between inputs and validated outputs. Name the artifacts, define success checks, and refuse silent partial completion.

Step 1: Shortlist candidates with the Screener API

When working through Step 1: Shortlist candidates with the Screener API, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Record timings and token or query cost next to functional results. Cost visibility early prevents surprise bills when the path moves from demo to shared environments. Log tool name, args hash, latency, and outcome for every call. Debugging agent loops without that trail wastes hours.

import requests
API_TOKEN = "YOUR_EODHD_API_TOKEN"
def get_candidates():
    url = "https://eodhd.com/api/screener"
    params = {
        "api_token": API_TOKEN,
        "sort": "market_capitalization.desc",
        "filters": '[["market_capitalization",">",1000000000],'
                   '["exchange","=","us"],'
                   '["sector","=","Technology"]]',
        "limit": 20,
        "fmt": "json",
    }
    response = requests.get(url, params=params)
    return response.json()["data"]
candidates = get_candidates()
tickers = [c["code"] for c in candidates]
print(tickers)

Step 2: Pull fundamentals for each candidate

When working through Step 2: Pull fundamentals for each candidate, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Keep configuration outside application code. Environment files, secret stores, and feature flags belong in one place operators can audit without reading the whole graph. Log tool name, args hash, latency, and outcome for every call. Debugging agent loops without that trail wastes hours.

def get_fundamentals(symbol):
    url = f"https://eodhd.com/api/fundamentals/{symbol}.US"
    params = {"api_token": API_TOKEN, "fmt": "json"}
    data = requests.get(url, params=params).json()
highlights = data.get("Highlights", {})
    return {
        "pe_ratio": highlights.get("PERatio"),
        "peg_ratio": highlights.get("PEGRatio"),
        "profit_margin": highlights.get("ProfitMargin"),
        "eps_growth": highlights.get("EPSEstimateNextYear"),
    }

Step 3: Check recent price action

When working through Step 3: Check recent price action, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Document the happy path and the recovery path together. Retries, human gates, and dead-letter handling are part of the product, not later polish. Log tool name, args hash, latency, and outcome for every call. Debugging agent loops without that trail wastes hours. When working through Step 3: Check recent price action, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Treat this stage as a contract between inputs and validated outputs. Name the artifacts, define success checks, and refuse silent partial completion.

import pandas as pd
from datetime import date, timedelta
def get_price_trend(symbol):
    url = f"https://eodhd.com/api/eod/{symbol}.US"
    params = {
        "api_token": API_TOKEN,
        "period": "d",
        "order": "d",
        "from": (date.today() - timedelta(days=90)).isoformat(),
        "fmt": "json",
    }
    prices = requests.get(url, params=params).json()
    df = pd.DataFrame(prices)
    last_close = df.iloc[0]["close"]
    month_ago_close = df.iloc[21]["close"] if len(df) > 21 else df.iloc[-1]["close"]
    change_pct = ((last_close - month_ago_close) / month_ago_close) * 100
    return {"last_close": last_close, "change_30d_pct": round(change_pct, 2)}

Step 4: Read the news sentiment

Step 4: Read the news sentiment works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Record timings and token or query cost next to functional results. Cost visibility early prevents surprise bills when the path moves from demo to shared environments. Expose tools with narrow schemas and explicit side-effect labels. Hosts need to know which calls mutate state before they auto-approve.

def get_sentiment(symbol):
    url = "https://eodhd.com/api/sentiments"
    params = {
        "s": f"{symbol}.US",
        "api_token": API_TOKEN,
        "from": (date.today() - timedelta(days=14)).isoformat(),
        "fmt": "json",
    }
    data = requests.get(url, params=params).json()
    entries = data.get(f"{symbol}.US", [])
    if not entries:
        return {"avg_sentiment": None}
avg = sum(e["normalized"] for e in entries) / len(entries)
    return {"avg_sentiment": round(avg, 3)}

Step 5: Combine everything into a single score

Step 5: Combine everything into a single score works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Keep configuration outside application code. Environment files, secret stores, and feature flags belong in one place operators can audit without reading the whole graph. Expose tools with narrow schemas and explicit side-effect labels. Hosts need to know which calls mutate state before they auto-approve.

def score_opportunity(symbol):
    fundamentals = get_fundamentals(symbol)
    price = get_price_trend(symbol)
    sentiment = get_sentiment(symbol)
score = 0
    if fundamentals["pe_ratio"] and fundamentals["pe_ratio"] < 25:
        score += 1
    if fundamentals["profit_margin"] and fundamentals["profit_margin"] > 0.10:
        score += 1
    if price["change_30d_pct"] < -5:
        score += 1
    if sentiment["avg_sentiment"] and sentiment["avg_sentiment"] > 0.15:
        score += 1
    return {
        "symbol": symbol,
        "score": score,
        **fundamentals,
        **price,
        **sentiment,
    }
results = [score_opportunity(t) for t in tickers]
ranked = sorted(results, key=lambda r: r["score"], reverse=True)
for r in ranked[:5]:
    print(r["symbol"], "score:", r["score"], "| P/E:", r["pe_ratio"],
          "| 30d change:", r["change_30d_pct"], "%",
          "| sentiment:", r["avg_sentiment"])

Wiring this back into the agent

Wiring this back into the agent works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Document the happy path and the recovery path together. Retries, human gates, and dead-letter handling are part of the product, not later polish. Expose tools with narrow schemas and explicit side-effect labels. Hosts need to know which calls mutate state before they auto-approve. Wiring this back into the agent works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Treat this stage as a contract between inputs and validated outputs. Name the artifacts, define success checks, and refuse silent partial completion.

From Here You Can Build

For From Here You Can Build, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Record timings and token or query cost next to functional results. Cost visibility early prevents surprise bills when the path moves from demo to shared environments. Authenticate at the gateway and re-authorize at the data plane. A bearer token alone is not a tenancy boundary.

Key Takeaways

For Key Takeaways, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Keep configuration outside application code. Environment files, secret stores, and feature flags belong in one place operators can audit without reading the whole graph. Authenticate at the gateway and re-authorize at the data plane. A bearer token alone is not a tenancy boundary.

FAQs

For FAQs, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Document the happy path and the recovery path together. Retries, human gates, and dead-letter handling are part of the product, not later polish. Authenticate at the gateway and re-authorize at the data plane. A bearer token alone is not a tenancy boundary. For FAQs, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Treat this stage as a contract between inputs and validated outputs. Name the artifacts, define success checks, and refuse silent partial completion.

Operational checklist

Operational checklist works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope.

Prefer small, testable units over sprawling scripts. When a step fails, the failure should point at a single responsibility rather than a tangled pipeline.

Expose tools with narrow schemas and explicit side-effect labels. Hosts need to know which calls mutate state before they auto-approve.

Put human approval on edges that spend money or change production data. Compile-time wiring does not equal business completeness.

Write a short runbook: how to rotate keys, how to drain the queue, how to roll back the last ingest.

Keep configuration outside application code. Environment files, secret stores, and feature flags belong in one place operators can audit without reading the whole graph.

Before promoting the stack, freeze versions, capture a golden transcript for the critical path, and confirm rollback steps. Shared environments need rate limits, tenancy checks, and a clear owner for secret rotation. Prefer boring reliability over clever one-off demos.

Batch note for 5a103d42eb4a: keep provider keys out of the repo, set a per-session token ceiling, and store transcripts next to the eval fixtures so later model swaps stay comparable.