# How to Use LlamaIndex with FXMacroData: RAG, Agents, REST and MCP

Canonical: https://fxmacrodata.com/articles/how-to-use-llamaindex-with-fxmacrodata
Author: FXMacroData
Published: 2026-07-11T06:20:02Z

Use LlamaIndex with FXMacroData by separating macro facts from retrieval, indexing, agents, workflows, REST tools, and MCP tool discovery.

[LlamaIndex](https://developers.llamaindex.ai/python/framework/) is useful when an FX macro assistant needs retrieval, indexed evidence, tool calls, and agent workflows rather than a single model prompt. FXMacroData supplies the current macro facts: dated[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 LlamaIndex as the retrieval and agent layer, not as the macro data source. Fetch FXMacroData evidence through REST or MCP, turn the returned rows into indexed documents or read-only tools, and then let a LlamaIndex agent answer over that checked evidence with clear timestamps and data gaps.

The important boundary is simple. LlamaIndex can index documents, retrieve relevant context, expose tools to agents, and coordinate typed workflows. FXMacroData should still answer "what printed, when did it print, what was the prior value, and what is coming next?" A model can summarize[US CPI](/api-data-docs/usd/inflation) ,[Non-Farm Payrolls](/api-data-docs/usd/non_farm_payrolls) , or a[Federal Reserve policy rate](/api-data-docs/usd/policy_rate) setup, but the source rows should come from FXMacroData first.

**Fit**

**Use this for**

RAG assistants, macro evidence search, agent tools, release-monitoring notes, and analyst workflows that need a durable index.

**Do not start with**

Model-only answers about recent macro prints, broker actions, or a vector index that stores stale facts without refresh checks.

**Best first build**

A read-only LlamaIndex agent that fetches FXMacroData rows, indexes the evidence, and returns a timestamp-aware briefing.

## Why LlamaIndex Fits FX Macro RAG

LlamaIndex is built around retrieval-augmented generation, indexes, query engines, tools, agents, and workflows. Its documentation describes RAG as loading and indexing external data, retrieving relevant context for a user query, and then sending that context to an LLM for response generation. That is a natural fit for FX macro research because the model needs current data that was not in its training set.

The practical split is to let FXMacroData own market facts and let LlamaIndex own retrieval, tool orchestration, and response synthesis. A desk can index recent macro evidence, use a query engine to search it, expose FXMacroData calls as agent tools, and still keep the source rows auditable.

**LlamaIndex finance workflow**

**1. Retrieve**

Call FXMacroData for calendar, announcement, FX, COT, commodity, or session data.

**2. Index**

Convert rows and notes into LlamaIndex documents with metadata and freshness fields.

**3. Answer**

Use a query engine or FunctionAgent to answer over checked evidence.

**4. Validate**

Reject output missing dates, values, tool paths, or data-gap warnings.

**Takeaway:**LlamaIndex makes the evidence easier to retrieve and route; FXMacroData supplies the evidence the answer is allowed to trust.

## REST, Index, Agent, or MCP: Which Path to Use

Do not start by exposing every possible tool to an agent. Start with the smallest controlled path that matches the job.

Path Use it when What owns macro facts Best first workflow**REST first**Your app controls credentials, logs, validation, retries, and cache policy. FXMacroData REST endpoints. Fetch calendar and announcement rows, then pass them into a prompt or index.**VectorStoreIndex**You need semantic retrieval over recent releases, notes, or policy commentary. FXMacroData rows plus your indexed document metadata. Index evidence documents and query them before the model writes.**FunctionAgent tools**The assistant needs to choose a read-only data tool during a conversation. FXMacroData tool wrappers. Expose a narrow function such as`get_usd_calendar`or`get_indicator_history`.**MCP tools**You want LlamaIndex to consume tools from an MCP server rather than custom wrappers. FXMacroData MCP. Convert the MCP server into LlamaIndex tool definitions and pass them to an agent.

## Prerequisites

You need a Python environment, a model provider supported by LlamaIndex, an FXMacroData API key, and a clear read-only scope for the first workflow.

```
pip install llama-index requests
pip install llama-index-tools-mcp
```

If you are building a vector-backed workflow, also choose a vector store. The examples below keep the index small so the shape is clear.

## Step 1: Fetch FXMacroData Evidence First

**What to do:**call FXMacroData before the model writes. For a[USD](/united-states)[inflation](/indicators/inflation) workflow, collect the[release calendar](/articles/how-to-schedule-with-release-calendar) , historical rows, and pair context.

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

Wrap the calls server-side. The model should receive evidence, not credentials.

```
import os

import requests

API_ROOT = "https://api.fxmacrodata.com/v1"
FXMD_API_KEY = os.environ["FXMD_API_KEY"]  # YOUR_API_KEY, kept server-side

def fxmd_get(path: str, api_key: str) -> dict:
    response = requests.get(
        f"{API_ROOT}/{path}",
        headers={"X-API-Key": api_key},
        timeout=10,
    )
    response.raise_for_status()
    return response.json()
```

**Why it matters:**LlamaIndex can improve retrieval and agent routing, but it should not become the only record of current macro values. Preserve the endpoint path, timestamp, currency, and response fields used in the final answer.

## Step 2: Build a Small Evidence Index

**What to do:**turn selected FXMacroData rows into LlamaIndex documents. LlamaIndex's VectorStoreIndex documentation explains that vector stores are a key component of RAG and can build indexes from documents or manually defined nodes.

```
from llama_index.core import Document, VectorStoreIndex

def evidence_documents(rows: list[dict]) -> list[Document]:
    return [
        Document(
            text=f"{row['date']} {row['indicator']} {row['val']}",
            metadata={
                "currency": row["currency"],
                "indicator": row["indicator"],
                "source": "FXMacroData",
            },
        )
        for row in rows
    ]

index = VectorStoreIndex.from_documents(evidence_documents(rows))
query_engine = index.as_query_engine()
```

Keep the index aligned with data freshness. A vector hit is useful only when the underlying macro row is still current and traceable.

**Indexing checklist**

**Metadata**

Store currency, indicator, date, endpoint path, and source name with every document.

**Freshness**

Rebuild or refresh the index after new releases, revisions, or calendar changes.

**Scope**

Keep the first corpus narrow: one currency, one release family, or one desk workflow.

## Step 3: Add Read-Only Agent Tools

**What to do:**expose narrow FXMacroData wrappers as LlamaIndex tools. The LlamaIndex tools guide describes`FunctionTool`as a wrapper around existing functions and`QueryEngineTool`as a way to turn a query engine into a tool.

```
from llama_index.core.agent.workflow import FunctionAgent
from llama_index.core.tools import FunctionTool
from llama_index.llms.openai import OpenAI

def get_usd_calendar() -> dict:
    """Fetch upcoming USD macro events from FXMacroData."""
    return fxmd_get("calendar/usd", FXMD_API_KEY)

calendar_tool = FunctionTool.from_defaults(
    get_usd_calendar,
    name="get_usd_calendar",
)

agent = FunctionAgent(
    tools=[calendar_tool],
    llm=OpenAI(model="gpt-5-mini"),
    system_prompt="Use FXMacroData evidence before writing.",
)
```

Keep the tool descriptions plain and narrow. The agent should know exactly what it can request and should not receive write-capable trading or account tools in the first version.

```
from llama_index.core.tools import QueryEngineTool

macro_search_tool = QueryEngineTool.from_defaults(
    query_engine,
    name="search_macro_evidence",
    description="Search indexed FXMacroData evidence by topic.",
)

agent = FunctionAgent(
    tools=[calendar_tool, macro_search_tool],
    llm=OpenAI(model="gpt-5-mini"),
)
```

## Step 4: Use FXMacroData MCP Tools

**What to do:**use MCP when you want LlamaIndex to consume tools from a hosted tool server. LlamaIndex documents MCP support through`llama-index-tools-mcp`, including converting an MCP server into LlamaIndex tool definitions and passing those tools to a`FunctionAgent`. Its MCP client supports SSE, streamable HTTP, and local-process transports, so the hosted FXMacroData MCP URL fits the streamable HTTP path.

```
from llama_index.tools.mcp import BasicMCPClient, McpToolSpec

mcp_client = BasicMCPClient(
    "https://mcp.fxmacrodata.com",
    headers={"Authorization": "Bearer YOUR_API_KEY"},
)

mcp_tool_spec = McpToolSpec(client=mcp_client)
tools = await mcp_tool_spec.to_tool_list_async()
```

Then pass those tools to the agent:

```
agent = FunctionAgent(
    tools=tools,
    llm=OpenAI(model="gpt-5-mini"),
    system_prompt=(
        "Use FXMacroData tools for macro facts. "
        "Separate evidence from interpretation."
    ),
)

response = await agent.run(
    "Summarize USD CPI risk for EUR/USD using current data."
)
```

If the host configures MCP directly, use the canonical FXMacroData MCP server URL:

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

Use MCP for tool discovery and host-level integrations. Use direct REST wrappers when your application needs strict control over credentials, request validation, retries, and logs.

## Step 5: Add Workflow and Output Guardrails

LlamaIndex Workflows are useful when the process needs typed steps, validation, streaming events, or shared per-run state. For finance, the first workflow should be boring: retrieve evidence, draft a briefing, check it, and stop.

```
Required output:
1. FXMacroData evidence used
2. Release dates and values
3. Interpretation
4. Data gaps or stale-data warnings
5. No broker action or trade execution
```

**Guardrail checklist**

- Fetch FXMacroData evidence before the agent writes.

- Store endpoint path, currency, indicator, date, and freshness metadata with every indexed document.

- Reject output that lacks dates, actual values, prior values, or missing-data warnings.

- Refresh the index after important releases and revisions.

- Keep broker execution and account operations outside the LlamaIndex tool set.

The safer production pattern is "research only." The agent can retrieve, search, and write an analyst note. A separate human or system can decide what to do with that note.

## Sources and References

- [LlamaIndex Framework documentation](https://developers.llamaindex.ai/python/framework/)

- [LlamaIndex Introduction to RAG](https://developers.llamaindex.ai/python/framework/understanding/rag/)

- [LlamaIndex VectorStoreIndex guide](https://developers.llamaindex.ai/python/framework/module_guides/indexing/vector_store_index/)

- [LlamaIndex Agents guide](https://developers.llamaindex.ai/python/framework/module_guides/deploying/agents/)

- [LlamaIndex Tools guide](https://developers.llamaindex.ai/python/framework/module_guides/deploying/agents/tools/)

- [LlamaIndex Workflows documentation](https://developers.llamaindex.ai/python/llamaagents/workflows/)

- [Using MCP tools with LlamaIndex](https://developers.llamaindex.ai/python/framework/module_guides/mcp/llamaindex_mcp/)

- [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 Cohere Command A with FXMacroData](/articles/how-to-use-cohere-command-with-fxmacrodata)

- [How to Use Perplexity Sonar with FXMacroData](/articles/how-to-use-perplexity-sonar-with-fxmacrodata)

- [Using Llama for Trading FX Macro Agents](/articles/using-llama-for-trading-fx-macro-agents)

Source: FXMacroData
