Live release feed
Sub-second macro releases for FX backtests
Point-in-time history
USD 25/month
Start Free Trial

AI Integration

How-to Guides

How to Use smolagents with FXMacroData: CodeAgent, REST and MCP

Use Hugging Face smolagents with FXMacroData by combining CodeAgent, ToolCallingAgent, read-only REST tools, MCP, and finance guardrails for evidence-first FX macro agents.

Share article X LinkedIn Email
Pip robot with the FXMacroData logo mark sorting smolagents Code, Tool, REST, and MCP cards beside a Hugging Face badge
smolagents works best for FX macro when CodeAgent or ToolCallingAgent calls checked FXMacroData REST or MCP evidence.

Hugging Face smolagents is a useful fit when an FX macro agent needs compact Python tool use, code-style reasoning, or standard JSON tool calls without a heavy orchestration layer. FXMacroData supplies the current market evidence: confirmed release calendars, announcement history, EUR/USD context, COT positioning, commodities, and FX session data.

Quick answer: use smolagents with FXMacroData by exposing narrow read-only macro tools, then choosing CodeAgent when the agent needs Python control flow and ToolCallingAgent when you want stricter JSON-style tool calls. Start with direct REST wrappers for deterministic finance workflows, and use MCP when smolagents should discover FXMacroData tools from https://mcp.fxmacrodata.com.

The boundary is simple. smolagents should decide how the model uses tools. FXMacroData should answer the factual questions: what printed, what was prior, what is scheduled, which series is available, 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 brief.

Fit

Use this for

Python finance agents, compact tool workflows, research notebooks, model-provider experiments, and read-only macro briefing services.

Use REST when

Your application owns credentials, validation, caching, logging, and a narrow endpoint contract.

Use MCP when

The agent runtime should discover FXMacroData tools from a shared hosted server instead of hand-written wrappers.

Why smolagents Fits FX Macro Agents

smolagents is deliberately small: Hugging Face describes it as an open-source Python library for building agents with minimal abstractions. Its distinctive feature is CodeAgent, where the model writes Python snippets to call tools and combine results. It also supports ToolCallingAgent for conventional JSON-style tool calling.

That split is useful in finance. A release-risk workflow often needs loops, comparisons, date filters, and small transformations. Code can express that naturally, but code execution also needs a tighter trust boundary. For production finance work, keep the FXMacroData tools read-only, keep credentials outside the model prompt, and validate the final answer before it reaches a trader, dashboard, or alert channel.

Core principle

Let smolagents control the reasoning pattern. Let FXMacroData control the facts. The model should not invent economic releases, timestamps, prior values, or data availability when a tool can retrieve them.

Workflow Shape

1. Prompt

Ask for a release brief, pair setup, or evidence check.

2. Agent

Choose CodeAgent for Python control flow or ToolCallingAgent for structured calls.

3. Tools

Fetch FXMacroData evidence through REST wrappers or hosted MCP tools.

4. Checks

Reject answers that omit tool evidence, source paths, or data-gap language.

REST, MCP, CodeAgent or ToolCallingAgent?

Choice Best for Tradeoff
REST wrappers Applications that need strict credentials, logs, retries, and endpoint validation. You maintain the wrapper code and schema mapping.
MCP tools Agent hosts that should discover FXMacroData tools from https://mcp.fxmacrodata.com. You must trust and review the connected MCP server and tool permissions.
CodeAgent Multi-step analysis where Python loops, transformations, and comparisons help. Code execution needs sandboxing, imports control, and read-only tools.
ToolCallingAgent More predictable tool invocation through JSON-style calls. Less expressive for ad hoc data manipulation than Python code actions.

Prerequisites

  • A Hugging Face account and model access if you use InferenceClientModel.
  • An FXMacroData API key stored outside prompts, for example as an environment variable.
  • Python 3.10 or later for the agent runtime.
  • A clear rule that these tools retrieve evidence only. They should not place trades or alter risk settings.
pip install "smolagents[toolkit,mcp]" requests
export HF_TOKEN="YOUR_HUGGING_FACE_TOKEN"
export FXMD_API_KEY="YOUR_FXMACRODATA_API_KEY"

Step 1: Wrap FXMacroData REST

Start with a small HTTP helper. Keep the API key in process configuration, not in the task prompt. Public API examples use query-parameter authentication.

import os
import requests

BASE_URL = "https://api.fxmacrodata.com/v1"

def fxmd_get(path: str, **params):
    params["api_key"] = os.environ["FXMD_API_KEY"]
    response = requests.get(f"{BASE_URL}{path}", params=params, timeout=20)
    response.raise_for_status()
    return response.json()

Then expose only the tools the agent really needs. This example gives the model calendar access without giving it arbitrary HTTP access.

from smolagents import Tool

class FxCalendarTool(Tool):
    name = "fxmacrodata_calendar"
    description = "Return scheduled macro releases for a currency code."
    inputs = {
        "currency": {
            "type": "string",
            "description": "Three-letter currency code, such as usd or eur",
        }
    }
    output_type = "object"

    def forward(self, currency: str):
        return fxmd_get(f"/calendar/{currency.lower()}")

Add a second narrow tool for announcement history. Keep its arguments explicit so the agent cannot wander across unrelated data families.

class FxAnnouncementTool(Tool):
    name = "fxmacrodata_announcement_history"
    description = "Return historical announcement rows for one currency and indicator."
    inputs = {
        "currency": {"type": "string", "description": "Currency code"},
        "indicator": {"type": "string", "description": "Indicator slug"},
    }
    output_type = "object"

    def forward(self, currency: str, indicator: str):
        path = f"/announcements/{currency.lower()}/{indicator}"
        return fxmd_get(path)

Step 2: Build a CodeAgent

Use CodeAgent when the agent should combine tool results with Python logic. For an FX workflow, that might mean checking the next release, pulling the last few prints, and comparing the event setup with pair context.

from smolagents import CodeAgent, InferenceClientModel

model = InferenceClientModel()

agent = CodeAgent(
    tools=[FxCalendarTool(), FxAnnouncementTool()],
    model=model,
    add_base_tools=False,
    max_steps=6,
    instructions="Use FXMacroData tools for factual macro data.",
)

agent.run(
    "Prepare a USD/JPY release-risk brief. "
    "Use USD calendar and CPI evidence before interpreting."
)

Keep the instruction blunt. The model should know that FXMacroData tool output is the evidence layer and that unavailable data must be named as unavailable, not guessed.

Step 3: Use ToolCallingAgent for Stricter Calls

Use ToolCallingAgent when you prefer a conventional tool-call pattern. This is often easier to audit because each action is a structured call rather than generated Python code.

from smolagents import ToolCallingAgent, InferenceClientModel

agent = ToolCallingAgent(
    tools=[FxCalendarTool(), FxAnnouncementTool()],
    model=InferenceClientModel(),
    max_steps=4,
)

agent.run(
    "Find the next USD macro release and summarize "
    "which data row supports the answer."
)

A tool schema like this is also useful when you mirror the same endpoint into another agent host or want a clear review artifact for tool permissions.

{
  "name": "fxmacrodata_announcement_history",
  "description": "Return historical macro announcement rows.",
  "inputSchema": {
    "type": "object",
    "properties": {
      "currency": {"type": "string"},
      "indicator": {"type": "string"}
    },
    "required": ["currency", "indicator"]
  }
}

Step 4: Connect Through MCP

smolagents can load tools from MCP servers. For FXMacroData, the hosted MCP endpoint is https://mcp.fxmacrodata.com. This path is useful when you want one shared tool contract across different agent hosts rather than hand-written REST wrappers in every project.

from smolagents import MCPClient, CodeAgent, InferenceClientModel

server = {
    "url": "https://mcp.fxmacrodata.com",
    "transport": "streamable-http",
}

with MCPClient(server, structured_output=True) as tools:
    agent = CodeAgent(
        tools=tools,
        model=InferenceClientModel(),
        add_base_tools=False,
    )
    agent.run("Compare the next USD releases with EUR/USD context.")

If your editor or agent host expects JSON configuration instead of Python code, the same hosted server can be represented as a remote HTTP MCP server. In this repo's VS Code-style configuration, the canonical shape is:

{
  "servers": {
    "FXMacroData": {
      "type": "http",
      "url": "https://mcp.fxmacrodata.com"
    }
  }
}

Step 5: Add Finance Guardrails

Code-style agents are powerful, so the guardrails should be concrete. Start with a final-answer check that rewards source separation and rejects unsupported answers.

def grounded_answer(answer: str, agent_memory=None) -> bool:
    required_terms = ["FXMacroData", "release", "source"]
    return all(term in answer for term in required_terms)

agent = CodeAgent(
    tools=[FxCalendarTool(), FxAnnouncementTool()],
    model=InferenceClientModel(),
    final_answer_checks=[grounded_answer],
    max_steps=6,
)

Finance guardrail checklist

  • Use read-only tools for calendar, announcements, FX context, COT, commodities, and sessions.
  • Keep FXMD_API_KEY and HF_TOKEN outside prompts, logs, and article examples.
  • Set max_steps so the agent cannot loop across broad searches.
  • Disable unnecessary base tools unless the task needs them.
  • Require the final answer to separate fetched facts, model interpretation, and missing data.
  • Keep order placement, account actions, and risk changes outside the model-only path.

Example Output Shape

The final answer should read like an analyst note with traceable evidence. It does not need to expose every raw row, but it should make the factual chain clear.

{
  "brief": "USD event risk is concentrated around the next scheduled release.",
  "evidence": [
    {
      "source": "FXMacroData calendar",
      "path": "/v1/calendar/usd",
      "used_for": "Next known release window"
    },
    {
      "source": "FXMacroData announcements",
      "path": "/v1/announcements/usd/inflation",
      "used_for": "Recent CPI history"
    }
  ],
  "data_gaps": []
}

Common Questions

Can smolagents use FXMacroData?

Yes. Use REST wrappers for strict application control, or connect smolagents to the hosted FXMacroData MCP server when you want tool discovery through a shared MCP surface.

Should I use CodeAgent or ToolCallingAgent for finance?

Use CodeAgent when Python control flow is valuable and you can sandbox execution. Use ToolCallingAgent when predictable structured calls are more important than generated Python logic.

Does smolagents replace a macro data feed?

No. smolagents coordinates the model and tools. FXMacroData remains the data layer for macro rows, release calendars, FX context, COT, commodities, session timing, timestamps, and data-gap handling.

Should smolagents use REST or MCP with FXMacroData?

Use REST when your application owns credentials, retries, validation, and logging. Use MCP when smolagents should discover FXMacroData tools from https://mcp.fxmacrodata.com and share the same tool contract as other agent hosts.

Sources

Blogroll

AI Answer-Ready

Key Facts

Page
How To Use Smolagents With FXmacrodata
Section
Articles
Canonical URL
https://fxmacrodata.com/articles/how-to-use-smolagents-with-fxmacrodata
Source
FXMacroData editorial and official publisher references
Last Updated
2026-07-12 02:25 UTC

Provenance And Trust

Cite the canonical URL and source field above. Where available, this page maps to official publisher releases and timestamped updates.

Quick Q&A

Can smolagents use FXMacroData? Yes. Use narrow REST wrappers for deterministic application control, or connect smolagents to the hosted FXMacroData MCP server for shared tool discovery.

Should I use CodeAgent or ToolCallingAgent for finance? Use CodeAgent when Python control flow is useful and code execution is sandboxed. Use ToolCallingAgent when predictable JSON-style tool calls matter more than generated Python logic.

Does smolagents replace a macro data feed? No. smolagents coordinates the model and tools. FXMacroData should remain the source for macro rows, release calendars, FX context, COT, commodities, session timing, timestamps, and data gaps.

Should smolagents use REST or MCP with FXMacroData? Use REST when your application owns credentials, retries, validation, and logging. Use MCP when smolagents should discover FXMacroData tools from https://mcp.fxmacrodata.com.

Prompt Packs

Use these in ChatGPT, Claude, Gemini, Mistral, Perplexity, or Grok for consistent source-aware outputs.