Use the Narwhal API with LangChain

Use LangChain and Narwhal to ask natural-language questions about holidays, release dates, economics, commodities, FX and predictions. Connect your agent to Narwhal through MCP with your API key, load the read-only tools, and let the agent choose a tool for each question.

What you'll set up

LangChain connects your agent to Narwhal's read-only MCP tools, and you end up with a Python script that asks a question about each data area. The connection uses langchain-mcp-adapters to load the tools and create_react_agent from langgraph.prebuilt to build the agent. Narwhal has one account and one API key across its data APIs, and REST and MCP share that key. The script connects to https://api.narwhalapi.com/mcp with an Authorization: Bearer YOUR_KEY header. Its prompts are plain questions; the agent chooses which tool to call.

Set your API key

  1. Create a free key Create your free key at narwhalapi.com/signup. Use this Narwhal key for the MCP connection in the script; the same key also works with the REST API.
  2. Store the key in your environment Keep your key in an environment variable called NARWHAL_API_KEY. Replace YOUR_KEY with your key before entering the command, then start the script from that environment. The Python connection reads this variable to form the Bearer header.
    Store your Narwhal key
    export NARWHAL_API_KEY="YOUR_KEY"

Pull data with code

The MCP connection uses streamable_http as its transport. MultiServerMCPClient holds the server URL and authorization header, and get_tools() supplies the read-only tools to the agent. In the script, the question text and connection settings are separate: the URL stays in the client configuration, while each user message comes from PROMPTS. You can ask about an area without putting an endpoint or a tool name into the question.

  1. Install the packages Install the MCP adapter, LangGraph and the model integration used by the script. The adapter supplies MultiServerMCPClient, while LangGraph supplies the prebuilt agent used to call the Narwhal tools.
    Install the agent packages
    pip install langchain-mcp-adapters langgraph langchain-anthropic
  2. Save the agent script Save the following code as agent.py. It loads the tools with await client.get_tools(), builds the agent and sends each question in PROMPTS as a user message. Each printed answer is the content of the final message returned by the agent.
Load the Narwhal tools and ask one question per area
import asyncio, os
from langchain_mcp_adapters.client import MultiServerMCPClient
from langgraph.prebuilt import create_react_agent

PROMPTS = {
    "holidays": "Is 25 December 2026 a public holiday in the United States?",
    "release dates": "When is the US CPI release in November 2026?",
    "economics": "What is the latest US CPI index and its month-on-month change?",
    "commodities": "What is the Brent spot price in dollars a barrel?",
    "FX": "What are the USD/EUR and USD/IDR rates?",
    "predictions": "What are the Fed rate odds for its next meeting?",
}

async def main():
    client = MultiServerMCPClient({
        "narwhal": {
            "transport": "streamable_http",
            "url": "https://api.narwhalapi.com/mcp",
            "headers": {"Authorization": f"Bearer {os.environ['NARWHAL_API_KEY']}"},
        }
    })
    tools = await client.get_tools()
    agent = create_react_agent("anthropic:claude-sonnet-5-5", tools)
    for area, question in PROMPTS.items():
        result = await agent.ainvoke({"messages": [("user", question)]})
        print(area, "->", result["messages"][-1].content)

asyncio.run(main())
  1. Start the agent Run the saved file from the environment that holds your Narwhal key. To ask a different question, change the relevant prompt text. Keep prompts as natural-language questions so the agent can choose the tool.
    Run the saved script
    python agent.py

The area samples use the same agent and PROMPTS from the complete script. Place a sample inside main() after the agent is built to ask that area's question and print its answer. The REST URL beside each sample identifies the corresponding data endpoint and the response field it returns.

Run it on a schedule

Run python agent.py from cron or your app's scheduler, with NARWHAL_API_KEY available to the script. The scheduled script follows the same prompt loop as a manual invocation. Set the questions in PROMPTS to the questions you want the agent to ask when that script starts.

Each tool call is one request against your key's quota. The schedule starts the script; the agent chooses tools in response to the questions in it. If you want to restrict which tools the scheduled agent can use, filter the tools list before passing it to create_react_agent.

Holidays with LangChain

Ask whether 25 December 2026 is a public holiday in the United States. The holiday tool is calendars_list_holidays. For the corresponding REST data, https://api.narwhalapi.com/v1/calendars/holidays/USA/2026 returns holidays, whose entries have date and name. The sample sends the holiday question from PROMPTS to the agent.

Ask about holidays
result = await agent.ainvoke({
    "messages": [("user", PROMPTS["holidays"])]
})
print(result["messages"][-1].content)

Release dates with LangChain

Ask when the US CPI release falls in November 2026. The release-date tool is economics_list_releases. The corresponding REST URL is https://api.narwhalapi.com/v1/economics/calendar?countries=USA&start_date=2026-11-01&end_date=2026-11-30&limit=100. Read releases for entries with at, period, topic and status. This question asks for a release date in the economic calendar.

Ask about release dates
result = await agent.ainvoke({
    "messages": [("user", PROMPTS["release dates"])]
})
print(result["messages"][-1].content)

Economics with LangChain

Ask for the US CPI index and its month-on-month change using the economics prompt. The CPI tool is economics_get_cpi. The corresponding REST URL, https://api.narwhalapi.com/v1/economics/USA/cpi/observations?start=2025-09, returns observations, with period and value in each entry. The agent receives the question and selects a tool to answer it. Narwhal economics data includes CPI, inflation, GDP and yields. In the CPI response, period identifies the observation period and value holds the observation value; the prompt asks the agent for an index and a month-on-month change.

Ask about economics
result = await agent.ainvoke({
    "messages": [("user", PROMPTS["economics"])]
})
print(result["messages"][-1].content)

Commodities with LangChain

Ask for the Brent spot price in dollars a barrel. The spot-price tool is commodities_get_spot_price. The corresponding REST URL is https://api.narwhalapi.com/v1/commodities/spot/BRENT/USD, and its response has a price field. Commodity spot codes include, for example, XAU, XAG, XPT, XPD, XCU, BRENT and WTI.

Ask about commodities
result = await agent.ainvoke({
    "messages": [("user", PROMPTS["commodities"])]
})
print(result["messages"][-1].content)

FX with LangChain

Ask for USD/EUR and USD/IDR rates with the FX prompt. The exchange-rate tool is fx_get_rates. The corresponding REST URL, https://api.narwhalapi.com/v1/fx/rates/USD?currencies=EUR,IDR, returns rates, with currency and rate in each entry. Both currency pairs are part of the same question sent to the agent.

Ask about FX
result = await agent.ainvoke({
    "messages": [("user", PROMPTS["FX"])]
})
print(result["messages"][-1].content)

Predictions with LangChain

Ask for Fed rate odds using the predictions prompt. The policy-path tool is predictions_get_policy_path. The corresponding REST URL is https://api.narwhalapi.com/v1/predictions/policy-paths/federal-reserve. Its meetings entries have resolves_at, p_cut, p_hold and p_hike, for the meeting resolution time and the probabilities of a cut, hold or hike. Use the resolution time to identify the meeting associated with those probabilities. The example question asks for rate odds, and the agent receives that question as a user message.

Ask about predictions
result = await agent.ainvoke({
    "messages": [("user", PROMPTS["predictions"])]
})
print(result["messages"][-1].content)

Do tool calls cost requests?

Yes. Request use follows the tool calls the agent makes. Loading a list of questions into PROMPTS does not define which tools the agent will choose for those questions. Account for its tool calls when you schedule the script.

How do I limit the tools?

Filter the list returned by get_tools() by name before passing it to the agent. Names include economics_get_cpi, economics_list_releases, calendars_list_holidays, commodities_get_spot_price, fx_get_rates and predictions_get_policy_path. Pass the filtered list as the tools argument to create_react_agent so the agent has the tools you selected.

Published .