# How to Use Pydantic AI with FXMacroData: Typed Agents, REST and MCP

Canonical: https://fxmacrodata.com/articles/how-to-use-pydantic-ai-with-fxmacrodata
Author: FXMacroData
Published: 2026-07-11T08:06:18Z

Use Pydantic AI with FXMacroData by combining typed agents, read-only REST tools, structured output, MCP, and finance validation guardrails.

[Pydantic AI](https://pydantic.dev/docs/ai/core-concepts/agent/) 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](/dashboard/release-calendar) , announcement history,[EUR/USD](/dashboard/EUR_USD) context,[COT](/dashboard/cot) positioning,[commodities](/dashboard/commodities) , and[FX session](/dashboard/fx-sessions) data.

**Quick answer:**use Pydantic AI when you want a finance agent to call read-only FXMacroData tools and return a validated Python object, not loose prose. Start with direct REST wrappers for strict control, add structured output models for evidence and warnings, and use FXMacroData MCP when the agent should discover tools from`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](/api-data-docs/usd/inflation) ,[Non-Farm Payrolls](/api-data-docs/usd/non_farm_payrolls) , a[Federal Reserve policy rate](/api-data-docs/usd/policy_rate) decision, or a[USD/JPY](/dashboard/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](/united-states) 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 send the API key in the`X-API-Key`header:

```
curl -H "X-API-Key: YOUR_API_KEY" "https://api.fxmacrodata.com/v1/calendar/usd"
curl -H "X-API-Key: YOUR_API_KEY" "https://api.fxmacrodata.com/v1/announcements/usd/inflation"
curl -H "X-API-Key: YOUR_API_KEY" "https://api.fxmacrodata.com/v1/forex/eur/usd"
curl -H "X-API-Key: YOUR_API_KEY" "https://api.fxmacrodata.com/v1/commodities/latest"
```

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}",
        headers={"X-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. The URL form below keeps the example short; where your MCP client accepts custom headers, send the key as`Authorization: Bearer YOUR_API_KEY`instead of placing it in the URL.

```
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
```

**Practical rule:**if the agent cannot show which FXMacroData evidence it used, treat the answer as commentary rather than a research note.

## Sources and References

- [Pydantic AI agents documentation](https://pydantic.dev/docs/ai/core-concepts/agent/)

- [Pydantic AI function tools documentation](https://pydantic.dev/docs/ai/tools-toolsets/tools/)

- [Pydantic AI structured output documentation](https://pydantic.dev/docs/ai/core-concepts/output/)

- [Pydantic AI MCP overview](https://pydantic.dev/docs/ai/mcp/overview/)

- [Pydantic AI MCP client documentation](https://pydantic.dev/docs/ai/mcp/client/)

- [Pydantic AI models and providers overview](https://pydantic.dev/docs/ai/models/overview/)

- [FXMacroData API documentation](https://fxmacrodata.com/documentation)

- [FXMacroData MCP documentation](https://fxmacrodata.com/documentation/mcp-server)

- [FXMacroData production OpenAPI schema](https://api.fxmacrodata.com/openapi.json)

**Related FXMacroData AI integration guides**

- [How to Build LangGraph FX Macro Agents with FXMacroData](/articles/build-langgraph-fx-macro-agents-with-fxmacrodata)

- [How to Use LlamaIndex with FXMacroData](/articles/how-to-use-llamaindex-with-fxmacrodata)

- [How to Use CrewAI with FXMacroData](/articles/how-to-use-crewai-with-fxmacrodata)

- [How to Use Microsoft Agent Framework with FXMacroData](/articles/how-to-use-microsoft-agent-framework-with-fxmacrodata)

Source: FXMacroData
