# Build an agent

To add the DFO to an assistant you already use, such as Claude or ChatGPT, follow [Connect an assistant](/docs/start/connect-an-assistant).

The DFO MCP server gives an agent tools to search for, fetch, and analyse development finance data. It does not need an API key or sign-in, and it works with any client that implements MCP over streamable HTTP:

Server address: `https://developmentfinance.org/mcp`

Leave the trailing slash off the URL.

Use the MCP server when a model decides which data to fetch. For scripts and pipelines, use the [Python or TypeScript SDK](/docs/start/quickstart).

## Connect

An agent framework connects to the server, gives the tools to your model, and runs the tool-call loop. An MCP client library lets your code call the tools directly, and you pass the results to your model. The tabs below show examples of both. The framework examples use Gemini. Any model your framework supports works the same way.

**Pydantic AI**

[Pydantic AI](https://pydantic.dev/docs/ai/mcp/client/) (`uv add pydantic-ai`, or `pip install pydantic-ai`) takes the server as an `MCP` capability, which also passes the server's instructions to the model. Set `GOOGLE_API_KEY`, or change the model string to another provider.

```python
import asyncio

from pydantic_ai import Agent
from pydantic_ai.capabilities import MCP

agent = Agent(
    "google:gemini-flash-latest",
    capabilities=[MCP("https://developmentfinance.org/mcp")],
    retries={"tools": 3},
)


async def main():
    result = await agent.run("What is health spending per person in Kenya?")
    print(result.output)


asyncio.run(main())
```

The agent opens the connection when the run starts and closes it at the end.

**Google ADK**

The [Agent Development Kit](https://adk.dev/tools-custom/mcp-tools/) (`uv add "google-adk[mcp]"`, or `pip install "google-adk[mcp]"`) takes the server as an `McpToolset`. Set `GOOGLE_API_KEY`.

```python
import asyncio

from google.adk.agents import LlmAgent
from google.adk.runners import InMemoryRunner
from google.adk.tools.mcp_tool import McpToolset
from google.adk.tools.mcp_tool.mcp_session_manager import StreamableHTTPConnectionParams
from google.genai import types

dfo = McpToolset(
    connection_params=StreamableHTTPConnectionParams(
        url="https://developmentfinance.org/mcp",
        sse_read_timeout=60,
    )
)
root_agent = LlmAgent(
    model="gemini-flash-latest",
    name="dfo_agent",
    instruction="Answer questions about development finance with the DFO tools.",
    tools=[dfo],
)


async def main():
    async with InMemoryRunner(agent=root_agent) as runner:
        session = await runner.session_service.create_session(
            app_name=runner.app_name, user_id="user"
        )
        question = types.UserContent("What is health spending per person in Kenya?")
        async for event in runner.run_async(
            user_id=session.user_id, session_id=session.id, new_message=question
        ):
            if event.is_final_response() and event.content and event.content.parts:
                print("".join(part.text or "" for part in event.content.parts))


if __name__ == "__main__":
    asyncio.run(main())
```

Leaving the `async with` block closes the connection. Save the file as `agent.py` in a folder such as `dfo_agent/`. Run `adk run dfo_agent` or `adk web` from the folder's parent to load the same `root_agent`.

**FastMCP**

The [FastMCP client](https://gofastmcp.com/clients/client) (`uv add fastmcp`, or `pip install fastmcp`) lets your code call the tools directly.

```python
import asyncio

from fastmcp import Client


async def main():
    async with Client("https://developmentfinance.org/mcp") as client:
        tools = await client.list_tools()
        print([tool.name for tool in tools])

        result = await client.call_tool(
            "search",
            {
                "parts": [
                    {"variable": "health spending per person", "entities": [{"text": "Kenya"}]}
                ],
                "raw_query": "health spending per person in Kenya",
            },
            timeout=60,
            raise_on_error=False,
        )
        print(result.content[0].text)


asyncio.run(main())
```

**TypeScript**

The [MCP TypeScript SDK](https://ts.sdk.modelcontextprotocol.io/v2/) (`npm install @modelcontextprotocol/client`) connects over streamable HTTP and lets your code call the tools directly.

```ts
import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";

const client = new Client({ name: "my-agent", version: "1.0.0" });
await client.connect(
  new StreamableHTTPClientTransport(new URL("https://developmentfinance.org/mcp")),
);

const { tools } = await client.listTools();
console.log(tools.map((tool) => tool.name));

const result = await client.callTool({
  name: "search",
  arguments: {
    parts: [{ variable: "health spending per person", entities: [{ text: "Kenya" }] }],
    raw_query: "health spending per person in Kenya",
  },
});
for (const block of result.content) {
  if (block.type === "text") console.log(block.text);
}
await client.close();
```

In the client examples, `search` returns its interpretation of the question and the spec id that `get_data` takes. The first two lines of its result:

```text
"Kenya's health expenditure per capita in international dollars, 2000 to 2023. World Development Indicators."  [spec_0002907ee44bf25fc98f343372614a84]
confidence high · 24 observations · has data
```

Read the tool list from the server at runtime, because the available tools can change. [The MCP server](/docs/reference/mcp#tools) lists the current tools.

## Load DFO skills

Tool descriptions describe what the tools do. Skills describe how to choose and interpret DFO data, such as which measure of aid answers a question. A `search` result lists the skills that apply to its data, and `get_skill` loads a skill by id. [Add DFO skills to your assistant](/docs/start/add-skills) explains how to install them.

An agent that reads skills from a folder can load them before it calls the DFO. Every skill has a zip at `https://developmentfinance.org/docs/skills/<skill>.zip`. The zip contains one folder named after the skill, with `SKILL.md` and its `references/` folder inside. This script fetches `oda-measures` with [HTTPX](https://www.python-httpx.org) (`uv add httpx`, or `pip install httpx`) and unzips it into `skills/`:

```python
import io
import zipfile

import httpx

response = httpx.get("https://developmentfinance.org/docs/skills/oda-measures.zip")
response.raise_for_status()
zipfile.ZipFile(io.BytesIO(response.content)).extractall("skills")
```

Keep the folder intact, because `SKILL.md` refers to the files in `references/` by relative path. A zip is a copy of the skill on the day you fetch it, so fetch it again to pick up revisions.

To pass a skill to a model as text, fetch its Markdown at `https://developmentfinance.org/docs/skills/<skill>.md`. A reference file is at `https://developmentfinance.org/docs/skills/<skill>/references/<file>.md`. [What a skill is](/docs/start/skills#the-dfos-skills) describes the skills the DFO publishes.

## Handle refusals

When the server refuses a call, it returns a tool result marked as an error (`isError` in the protocol). The result's text gives the cause of the refusal, and its structured content has the fields your code can act on:

```json
{
  "code": "definition_not_held",
  "retry_mode": "correct_and_retry",
  "message": "No definition held for 'spec_00000000000000000000000000000000'. ...",
  "fix": {
    "definition_id": "spec_00000000000000000000000000000000",
    "next_step": "search"
  },
  "upstream_code": null,
  "retry_after_s": null,
  "capability_version": null
}
```

`retry_mode` sets what your loop does next:

| `retry_mode`         | What to do                                                                                        |
| -------------------- | ------------------------------------------------------------------------------------------------- |
| `correct_and_retry`  | Change the arguments to match `fix`, then call again.                                             |
| `refresh_then_retry` | The underlying data changed. Run the step in `fix.next_step` (often `get_data`), then call again. |
| `retry_after_delay`  | Wait `retry_after_s` seconds, then repeat the call with the same arguments.                       |
| `do_not_retry`       | Stop and tell the user. Repeating the call returns the same refusal.                              |

Pass the refusal text to the model as the tool result. The server writes that text for a model to follow.

By default, Pydantic AI sends the model the refusal's structured content as JSON in place of the text, so the model sees `message` and `fix`. A tool gets one retry by default. The next refusal in a row from that tool ends the run, so raise `retries` as the example does.

Google ADK passes the whole result to the model as the tool response: the refusal text, the structured fields, and `isError`.

FastMCP's `call_tool` raises `ToolError` on a refusal unless you pass `raise_on_error=False`, as the example does. With `raise_on_error=False`, `result.is_error` is true and `result.structured_content` contains the fields above.

The TypeScript SDK's `callTool` returns the refusal with `isError` set and the same fields in `structuredContent`. The SDK types `structuredContent` as `unknown`, so check its shape before reading `retry_mode`.

When your code runs the loop with an MCP client, handle `retry_after_delay` in code and pass every other refusal to the model.

## Time and rate limits

Every tool call responds within 45 seconds, so set your client's read or tool-call timeout higher. The Google ADK and FastMCP examples set 60 seconds. Pydantic AI waits 300 seconds by default, and the TypeScript SDK 60 seconds. Pass `{ timeout: 60_000 }` as the second argument of `callTool` to set it per call. A large `get_data` request can take longer than 45 seconds to build. Near the 45-second limit, the server refuses the call with code `operation_still_processing` and `retry_mode` set to `retry_after_delay` while the work continues. Repeating the call with the same arguments returns the result of that work, or the same refusal while the work continues.

The site allows 300 requests a minute to `/mcp` from one IP address, and an API key does not raise that limit. Above that limit, the server returns HTTP 429 with a `Retry-After` header in seconds. When total load across all callers is high, the server refuses the call with code `rate_limited`, `retry_mode` set to `retry_after_delay`, and a wait time in `retry_after_s`.
