> ## Documentation Index
> Fetch the complete documentation index at: https://macrofeed.dsforge.co/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Context API and SDK

> Call MacroFeed from TypeScript or Python using Context Query or Execute.

MacroFeed is delivered through Context Protocol. Your application authenticates with Context, and Context makes the authorized MCP request to MacroFeed. All calls go through Context API endpoints.

<Note>
  If you are adding MacroFeed to Cursor, Claude Code, OpenClaw, or another MCP client, start with [Connect in 60 seconds](/docs/connect). This page is for applications that call the Context SDK from their own server code.
</Note>

## Prerequisites

1. [Sign in to Context](https://www.ctxprotocol.com/) to create the embedded wallet.
2. Set the USDC spending cap and fund the wallet. The [official MCP prerequisites](https://docs.ctxprotocol.com/sdk/mcp) describe the current setup order.
3. Open [Context Settings](https://www.ctxprotocol.com/settings) and create an API key beginning with `sk_live_`.
4. Install the TypeScript or Python SDK in your server-side application.

### TypeScript

```bash theme={null}
npm install @ctxprotocol/sdk
```

### Python

```bash theme={null}
pip install ctxprotocol
```

Store the key in a server-side environment variable. The examples use `CONTEXT_API_KEY`; the variable name itself is your choice.

```bash theme={null}
CONTEXT_API_KEY=your_context_api_key
```

<Warning>
  Never expose the Context API key in browser code or a public `NEXT_PUBLIC_*` environment variable.
</Warning>

## Choose a mode

| Mode    | Best for                                                                           | Billing behavior                                                                               |
| ------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| Execute | Direct calendar lookups, backend workflows, and predictable arguments              | Per MacroFeed method call, accumulated inside an optional session budget                       |
| Query   | Natural-language questions that need tool selection, multiple calls, and synthesis | Context returns one managed answer; tool and model/orchestration costs are reported separately |

Discovery is free. MacroFeed's current Query listing price is `$0.00`, but a Query can still incur Context model/orchestration cost. Always inspect the returned `cost` object. Execute sessions provide the clearest hard spend envelope for deterministic integrations.

## Execute a tool

This example discovers MacroFeed, opens a session capped at `$0.01`, fetches the next USD CPI release, and closes the session so accrued calls can settle.

```ts theme={null}
import { ContextClient } from "@ctxprotocol/sdk";

const client = new ContextClient({
  apiKey: process.env.CONTEXT_API_KEY!,
});

const matches = await client.discovery.search("MacroFeed", 10);
const macroFeed = matches.find(
  (tool) => tool.id === "ca9e2cc7-f389-4f64-a301-f7cdc1b50a0e",
);

if (!macroFeed) {
  throw new Error("MacroFeed is not available in Context discovery");
}

const started = await client.tools.startSession({
  maxSpendUsd: "0.01",
});
const sessionId = started.session.sessionId;

try {
  const response = await client.tools.execute({
    toolId: macroFeed.id,
    toolName: "get_next_release",
    args: {
      currency: "USD",
      indicatorKey: "us_cpi_headline",
    },
    sessionId,
  });

  console.log(response.result);
  console.log(response.method.executePriceUsd);
  console.log(response.session.spent);
} finally {
  await client.tools.closeSession(sessionId);
}
```

`get_next_release` currently costs `$0.0004` per Execute call. The response contains MacroFeed's structured event object in `response.result`, plus method-price and session-spend metadata.

<Tip>
  Use `health_check` for a minimal connection test. Its current Execute price is `$0.0001`.
</Tip>

## Run a managed Query

Use Query when the caller has a question rather than a predetermined tool call. Context can discover, select, call, and combine MacroFeed methods before returning an answer with evidence.

```ts theme={null}
import { ContextClient } from "@ctxprotocol/sdk";

const client = new ContextClient({
  apiKey: process.env.CONTEXT_API_KEY!,
});

const answer = await client.query.run({
  query:
    "Using MacroFeed Economic Calendar, what is the next scheduled USD CPI release? Include its release time, actual, previous, and change from previous.",
  tools: ["ca9e2cc7-f389-4f64-a301-f7cdc1b50a0e"],
  responseShape: "answer_with_evidence",
  includeDeveloperTrace: true,
});

console.log(answer.response);
console.log(answer.evidence);
console.log(answer.toolsUsed);
console.log(answer.cost);
```

Passing the MacroFeed listing ID in `tools` constrains the managed run to this product. `includeDeveloperTrace` is useful during development for inspecting tool-call counts, retries, and fallback behavior.

## Use Python

The Python SDK exposes the same Query product surface. This example pins every run to MacroFeed.

```python theme={null}
import asyncio
import os

from ctxprotocol import ContextClient

MACROFEED_TOOL_ID = "ca9e2cc7-f389-4f64-a301-f7cdc1b50a0e"


async def main():
    async with ContextClient(
        api_key=os.environ["CONTEXT_API_KEY"],
    ) as client:
        answer = await client.query.run(
            query=(
                "What is the next scheduled USD CPI release? "
                "Include its release time and official source."
            ),
            tools=[MACROFEED_TOOL_ID],
            response_shape="answer_with_evidence",
        )

        print(answer.response)
        print(answer.evidence)
        print(answer.tools_used)
        print(answer.cost)


asyncio.run(main())
```

See the [official Python SDK reference](https://docs.ctxprotocol.com/sdk/python-reference) for Execute sessions, streaming, error handling, and response types.

## Build a recurring MacroFeed routine

For a daily brief, alert, or scheduled research job, keep the MacroFeed listing ID pinned so every run uses the same product surface. When your own agent will write the report, request evidence rather than a second synthesized answer.

```ts theme={null}
const evidence = await client.query.run({
  query:
    "Return the next seven days of high-impact USD events with release times and official sources.",
  tools: ["ca9e2cc7-f389-4f64-a301-f7cdc1b50a0e"],
  responseShape: "evidence_only",
  includeDataUrl: true,
});

console.log(evidence.evidence);
console.log(evidence.artifacts?.dataUrl);
```

Start by validating the question interactively, then schedule the same pinned Query in your agent framework or server job. The [official Agent Data Routines guide](https://docs.ctxprotocol.com/sdk/agent-routines) covers routine recipes, `evidence_only`, and full-data references.

## Production guidance

* Prefer Execute when your application already knows the MacroFeed method and arguments.
* Use a fresh, appropriately sized Execute session for each bounded workflow and close it in `finally`.
* Prefer Query for user-facing natural-language answers where synthesis is worth the additional model cost.
* Log `method.executePriceUsd`, `session.spent`, and Query `cost` metadata for billing visibility.
* Keep indicator keys stable in application code. Call `list_indicators` when users need discovery or taxonomy lookup.
* Treat `null` actual, previous, or change values as explicit data availability states, not zero.
* Forecast and surprise fields are reserved for compatibility; primary indicator response objects focus on official timing, actuals, previous values, and derived changes.
* For long Query jobs, follow the current polling guidance in the [official CTX MCP documentation](https://docs.ctxprotocol.com/sdk/mcp) rather than starting the same paid query twice.

## Request flow

```mermaid theme={null}
sequenceDiagram
  participant App as Your server
  participant CTX as Context API
  participant MCP as MacroFeed MCP
  App->>CTX: API key + Query or Execute request
  CTX->>MCP: Verified Context JWT + MCP tool call
  MCP-->>CTX: structuredContent matching outputSchema
  CTX-->>App: Result, evidence, and cost metadata
```

Your users do not need a separate MacroFeed API key. Context handles authorization, routing, and settlement between the calling application and MacroFeed.
