Pydantic AI is useful for FX research agents when the hardest part is not calling a model, but making the model return typed, reviewable output. FXMacroData supplies the current macro evidence: confirmed release calendars, announcement history, EUR/USD context, COT positioning, commodities, and FX session data.
https://mcp.fxmacrodata.com.
The core separation is simple. Pydantic AI coordinates the model, tools, typed dependencies, and final output. FXMacroData answers the market-data questions: what printed, when it printed, what the prior value was, what is scheduled next, and which dashboard a human can inspect. That matters for US CPI, Non-Farm Payrolls, a Federal Reserve policy rate decision, or a USD/JPY release-risk note.
Fit
Use this for
Typed analyst notes, release briefings, endpoint-backed model tools, validation-heavy research, and model-agnostic Python agent services.
Do not start with
A broad autonomous trader, browser-only research, untyped JSON, or a prompt that asks the model to remember recent macro values.
Best first build
A USD release briefing agent that fetches FXMacroData rows and returns a typed briefing with dates, values, gaps, and source paths.
Why Pydantic AI Fits FX Macro Agents
Pydantic AI agents are containers for instructions, function tools, toolsets, structured output types, typed dependencies, models, settings, and reusable capabilities. That maps well to finance because the useful output is rarely just a paragraph. A desk usually needs a typed object that names the evidence used, separates facts from interpretation, flags missing data, and can be stored or checked by software.
The practical value is validation. Pydantic AI can use function tools to retrieve data, Pydantic models to shape the final answer, and output validators when an answer is missing mandatory fields. FXMacroData then supplies the current macro rows that the model should reason over.
Typed macro-agent workflow
1. Ask
The user asks for a release briefing, scenario note, or macro-risk summary.
2. Fetch
A read-only FXMacroData tool returns dated rows and endpoint paths.
3. Shape
Pydantic AI asks the model for a structured briefing object.
4. Check
Validators reject stale, source-free, or gap-free answers before handoff.
Takeaway: Pydantic AI controls shape and validation; FXMacroData controls current macro evidence.
REST, Typed Tools, Structured Output, or MCP: Which Path to Use
Most teams should start with REST because it keeps credentials, retries, caching, and logs in application code. Add Pydantic AI tools when the model should decide which read-only data function to call. Add structured output from the first version. Use MCP when a reusable hosted tool server is a better fit than local wrappers.
| Path | Use it when | What Pydantic AI gets | Best first output |
|---|---|---|---|
| REST wrapper | Your service owns credentials, retries, validation, and logs. | A normal Python function returning FXMacroData JSON. | Evidence packet. |
| Function tool | The model should fetch only the data it needs during a run. | An @agent.tool function with typed arguments. |
Briefing with sources. |
| Structured output | The answer must be machine-checkable and storable. | A Pydantic model through output_type. |
Validated model object. |
| MCP | The agent should consume tools from a standard remote server. | FXMacroData tools from https://mcp.fxmacrodata.com. |
Tool-grounded briefing. |
Prerequisites
You need Python, Pydantic AI, a configured model provider, an FXMacroData API key, and a narrow first workflow. If you plan to connect to MCP from Pydantic AI, install the MCP extras or the full package.
pip install pydantic-ai requests
pip install "pydantic-ai-slim[mcp]"
For direct REST checks, use production FXMacroData endpoints and query-parameter authentication:
curl "https://api.fxmacrodata.com/v1/calendar/usd?api_key=YOUR_API_KEY"
curl "https://api.fxmacrodata.com/v1/announcements/usd/inflation?api_key=YOUR_API_KEY"
curl "https://api.fxmacrodata.com/v1/forex/eur/usd?api_key=YOUR_API_KEY"
curl "https://api.fxmacrodata.com/v1/commodities/latest?api_key=YOUR_API_KEY"
Keep the key server-side. The model should receive evidence and source paths, not credentials.
Step 1: Define the Typed Briefing Contract
What to do: define the final object you want the agent to return before wiring tools. This makes missing evidence visible.
from pydantic import BaseModel, Field
class MacroBriefing(BaseModel):
currency: str = Field(pattern="^[A-Z]{3}$")
topic: str
evidence_used: list[str] = Field(min_length=1)
key_values: list[str] = Field(min_length=1)
interpretation: str
data_gaps: list[str] = Field(default_factory=list)
human_review_required: bool = True
The output schema is intentionally small. A first version should prove the agent can fetch evidence, name it, and separate interpretation from missing data. Add fields later when a user workflow needs them.
Output contract
Evidence
Endpoint paths, currencies, indicators, and returned values used in the answer.
Interpretation
The analyst view generated from fetched data, not from memory.
Gaps
Explicit warnings for missing rows, stale data, empty results, or unavailable fields.
Step 2: Add FXMacroData as a Pydantic AI Tool
What to do: create a typed dependency object and one narrow FXMacroData tool. Pydantic AI tools are useful when the model needs extra information that should come from deterministic application code.
from dataclasses import dataclass
import os
import requests
@dataclass
class FxmdDeps:
api_key: str
api_root: str = "https://api.fxmacrodata.com/v1"
def fxmd_get(deps: FxmdDeps, path: str) -> dict:
response = requests.get(
f"{deps.api_root}/{path}",
params={"api_key": deps.api_key},
timeout=10,
)
response.raise_for_status()
return response.json()
Attach the wrapper to an agent with a structured output type:
from pydantic_ai import Agent, RunContext
agent = Agent(
"openai:gpt-5-mini",
deps_type=FxmdDeps,
output_type=MacroBriefing,
instructions=(
"Use FXMacroData before writing about current macro data. "
"Return endpoint paths, values, interpretation, and gaps."
),
)
@agent.tool
def fxmacrodata_calendar(ctx: RunContext[FxmdDeps], currency: str) -> dict:
"""Fetch confirmed macro calendar rows for a 3-letter currency."""
code = currency.lower().strip()
return {"endpoint": f"/v1/calendar/{code}", "data": fxmd_get(ctx.deps, f"calendar/{code}")}
deps = FxmdDeps(api_key=os.environ["FXMD_API_KEY"])
result = agent.run_sync("Prepare a USD release briefing.", deps=deps)
print(result.output.model_dump())
Keep tool names narrow. A first agent can expose calendar data only. Add announcement history, FX pair context, COT, commodities, or sessions when the question needs them.
| Tool | Purpose | Example endpoint |
|---|---|---|
fxmacrodata_calendar |
Find scheduled events for a currency. | /v1/calendar/usd |
fxmacrodata_announcement |
Fetch historical release rows. | /v1/announcements/usd/inflation |
fxmacrodata_pair_context |
Add FX pair context. | /v1/forex/eur/usd |
fxmacrodata_positioning |
Add positioning and cross-market context. | /v1/cot/usd |
A minimal tool schema should be easy for the model and reviewers to inspect:
{
"name": "fxmacrodata_calendar",
"description": "Fetch confirmed macro calendar rows for a currency.",
"parameters": {
"type": "object",
"properties": {
"currency": { "type": "string", "description": "3-letter currency code" }
},
"required": ["currency"]
}
}
Step 3: Use MCP When the Agent Should Discover Tools
What to do: use MCP when a Pydantic AI agent should connect to a remote tool server instead of relying only on local wrappers. Pydantic AI documents MCP client support through the recommended MCP capability and through MCPToolset, with Streamable HTTP recommended for remote servers and SSE treated as deprecated for new deployments.
The canonical FXMacroData MCP server is:
{
"servers": {
"FXMacroData": {
"type": "http",
"url": "https://mcp.fxmacrodata.com"
}
}
}
In Pydantic AI code, connect the remote MCP server as a toolset. Keep secrets in your runtime secret store where possible; the query-parameter form below is the explicit public example shape.
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPToolset
fxmd_toolset = MCPToolset(
"https://mcp.fxmacrodata.com?api_key=YOUR_API_KEY"
)
mcp_agent = Agent(
"openai:gpt-5-mini",
toolsets=[fxmd_toolset],
output_type=MacroBriefing,
)
result = await mcp_agent.run("Use FXMacroData tools for a USD briefing.")
print(result.output)
REST wrappers and MCP are not competing ideas. REST is best when your service owns every request boundary. MCP is best when a compatible host or agent runtime should discover a curated FXMacroData tool surface.
Step 4: Validate the Output Before Anyone Trusts It
What to do: reject answers that do not name evidence. Pydantic AI supports output validation, and finance workflows should use that step to enforce evidence, dates, and gap disclosure.
from pydantic_ai import ModelRetry
@agent.output_validator
def require_evidence(output: MacroBriefing) -> MacroBriefing:
if not output.evidence_used:
raise ModelRetry("Name the FXMacroData endpoint paths used.")
if not output.key_values:
raise ModelRetry("Include dated values or explain why unavailable.")
if output.human_review_required is not True:
raise ModelRetry("Keep human_review_required set to true.")
return output
Validation does not make a model a trader. It makes the model's output easier to reject before it reaches a research note, alert queue, dashboard annotation, or internal workflow.
Validation checklist
Source path
The output names the REST path or MCP tool used.
Value fields
Dates, actuals, priors, revisions, and availability warnings are explicit.
Review gate
The answer remains read-only and clearly marked for human review.
Step 5: Add Finance Guardrails
Pydantic AI gives you a clean way to bind model calls, tools, dependencies, and typed output. The production guardrails still belong in your application.
- Read-only first: expose calendar, announcements, FX, COT, commodities, and session data before any write-like surface.
- Evidence before prose: require an FXMacroData call before writing about current macro events.
- Small schemas: prefer narrow tools and one typed output model over a broad all-purpose agent.
- Gap disclosure: make empty results and missing fields part of the final output object.
- Human review: keep trade execution, account changes, and risk-limit changes outside the first agent.
Required briefing contract:
1. FXMacroData endpoint or MCP tool used
2. Currency, indicator, dates, and values
3. Prior and revised values where available
4. Interpretation separated from facts
5. Data gaps or stale-data warnings
6. Human review required
Common Questions
Can Pydantic AI use FXMacroData?
Yes. Use direct REST wrappers, Pydantic AI function tools, FXMacroData MCP, or a combination. REST gives your application the most control over credentials and logging. MCP is useful when the agent should discover tools from https://mcp.fxmacrodata.com.
Should Pydantic AI replace a macro data feed?
No. Pydantic AI coordinates models, tools, dependencies, and structured output. FXMacroData should remain the source for macro rows, release calendars, FX context, COT, commodities, session timing, timestamps, and data gaps.
Should I use REST or MCP with Pydantic AI?
Use REST when your application owns credentials, validation, retries, cache policy, and logs. Use MCP when a compatible agent host or Python service should discover FXMacroData tools through a standard server.
What is the main advantage of Pydantic AI for finance agents?
The main advantage is typed output and validation. A finance agent should return a checked object with evidence, values, gaps, and review status instead of an unstructured paragraph that is hard to audit.
Sources and References
- Pydantic AI agents documentation
- Pydantic AI function tools documentation
- Pydantic AI structured output documentation
- Pydantic AI MCP overview
- Pydantic AI MCP client documentation
- Pydantic AI models and providers overview
- FXMacroData API documentation
- FXMacroData MCP documentation
- FXMacroData production OpenAPI schema
Related FXMacroData AI integration guides