# Pydantic AI + Dizo

> Attach the Dizo MCP server to a Pydantic AI agent with MCPToolset and a bearer key, then get typed, validated prospect data back.

Type: MCP client — server URL `https://mcp.dizo.ai/mcp`. No native app needed.

## Steps
1. `pip install "pydantic-ai-slim[mcp]"` and export `DIZO_API_KEY`.
2. Create an `MCPToolset` with the Dizo URL and pass the key as `auth`.
3. Add it to `Agent(toolsets=[...])` and call `await agent.run(...)`.
4. Optional: keep servers in an `mcp_config.json` and load them with `load_mcp_toolsets()`.

## Where to go
`MCPServerStreamableHTTP` and HTTP authentication.

Open the Pydantic AI MCP docs: https://pydantic.dev/docs/ai/mcp/client/#streamable-http

## agent.py
```
import asyncio, os
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPToolset

dizo = MCPToolset("https://mcp.dizo.ai/mcp", auth=os.environ["DIZO_API_KEY"])

agent = Agent(
    "anthropic:claude-sonnet-5-5",
    toolsets=[dizo],
    instructions="Call dizo_quote before any job over 100 credits. Stop on a 402.",
)

async def main():
    result = await agent.run("Find 10 heads of RevOps at US fintechs with 100-1000 employees and their work emails.")
    print(result.output)

asyncio.run(main())
```

## mcp_config.json
```
{
  "mcpServers": {
    "dizo": {
      "url": "https://mcp.dizo.ai/mcp",
      "headers": { "Authorization": "Bearer ${DIZO_API_KEY}" }
    }
  }
}

# agent.py
# from pydantic_ai.mcp import load_mcp_toolsets
# agent = Agent("anthropic:claude-sonnet-5-5", toolsets=load_mcp_toolsets("mcp_config.json"))
```

## Notes
- The toolset opens and closes itself on each run. Wrap several runs in `async with agent:` to reuse one connection.
- `load_mcp_toolsets()` expands `${DIZO_API_KEY}`, so the key never sits in the config file. An unset variable raises an error.

## Related API docs
- [/docs/search](https://dizo.ai/docs/search.md)
- [/docs/email-find](https://dizo.ai/docs/email-find.md)
- [/docs/me](https://dizo.ai/docs/me.md)


## Pydantic AI and why typed agents suit contact data

Pydantic AI is a Python agent framework from the team behind Pydantic, the validation library. You define an `Agent` with a model and a set of tools or toolsets, run it with `await agent.run(...)`, and read the result from `result.output`. Its focus is type safety: inputs, tool arguments and outputs are described with Python types and checked at runtime, so mistakes surface as validation errors instead of quietly malformed data.

That focus matters more than usual when the data is people. A prospecting agent that returns a list of contacts is only useful if every row actually has a name, a title, a company domain and an email field you can trust to be what it claims. Pairing a typed framework with a data source that only charges when it finds something gives you a pipeline where both the shape and the substance of each record are checked before anything reaches your CRM or sequencer.

## What the Dizo toolset gives a Pydantic AI agent

Pydantic AI connects to MCP servers through `MCPToolset`. Point one at `https://mcp.dizo.ai/mcp` and the agent can see every Dizo tool: `dizo_search` for plain-English prospecting, `dizo_people_search` and `dizo_company_search` for structured filters, `dizo_count` for free market sizing, `dizo_best_contact` and `dizo_org_chart` for finding the right person, the email and phone finders, enrichment, reverse lookups, and the free account tools `dizo_quote`, `dizo_whoami` and `dizo_balance`.

Each tool description includes its credit cost, so the model can reason about price before it calls anything. Lookups that find nothing are free, and searches charge only for results returned: 1 credit per 25 results, or 0.04 credits per record. The full list with costs is on the [MCP server page](/mcp). Tasks that fit this pairing well:

- Return a validated list of 25 VPs of Finance at logistics companies, each with a work email or an explicit null.
- Take a company domain from a form, enrich it with `dizo_enrich_company`, and return a typed firmographic record.
- Resolve an inbound email address to a person and employer with `dizo_email_to_profile`.
- Find the right contact at 40 named accounts using a ranked title list.
- Count how many people match three different segment definitions, for free, and recommend one.
- Re-identify contacts whose emails bounced and return their current employer and work email.

## Setting up the toolset step by step

Install the slim package with the MCP extra: `pip install "pydantic-ai-slim[mcp]"`. Export your key as `DIZO_API_KEY`. While you build, use a `dz_test_` key. Test keys return synthetic data and never spend credits, so you can iterate on prompts and output models without a balance. [Sign up](/signup) to get a live key.

In code, create the toolset with the URL as the first argument and the key as `auth`: `MCPToolset("https://mcp.dizo.ai/mcp", auth=os.environ["DIZO_API_KEY"])`. Pydantic AI's docs describe `auth` as accepting a bearer token string for HTTP transports, which is exactly what Dizo expects in the `Authorization: Bearer` header. You can pass static headers through a `headers` argument instead if you prefer to set the header yourself.

Pass the toolset to `Agent("anthropic:claude-sonnet-5-5", toolsets=[dizo], instructions=...)` and await `agent.run()`. You do not have to open the connection yourself: the toolset opens and closes as needed on each run. If your process makes several runs in a row, wrap them in `async with agent:` so they share one connection instead of reconnecting each time.

## Keeping the key out of code with mcp_config.json

Teams that run several MCP servers often prefer configuration over code. Pydantic AI's `load_mcp_toolsets()` reads a JSON file with an `mcpServers` object, the same general shape many MCP clients use. For Dizo, the entry has a `url` and a `headers` object containing `Authorization: Bearer ${DIZO_API_KEY}`. The loader expands `${VAR}` references from the environment, so the file can be committed without the key.

Two details from the Pydantic AI docs are worth knowing. An undefined `${VAR}` raises a `ValueError` rather than silently sending an empty header, which is the behaviour you want for a secret. You can write `${VAR:-default}` for optional values, but do not give a default for the key itself. The docs also warn to load only config files you control, because a config entry can launch local commands. Treat the file like code and review changes to it.

## Controlling spend from the agent and the key

Pydantic AI gives you a clean place to state spending rules: the agent's `instructions`. Tell the model to call `dizo_quote` before any job likely to exceed about 100 credits, to call `dizo_whoami` at the start of a session to learn its caps and remaining budget, and to stop and report if it receives a 402. Those instructions shape behaviour, but they are requests to a model, not limits.

The limits live on the key. Create a dedicated key for this agent in the console or with `POST /v1/keys`, scoped to `data:read`, with `max_credits_per_request`, a daily cap, a monthly cap and an endpoint allow-list. MCP connections already default to `data:read` and a 500-credit per-call limit unless you change them. At the account level, a monthly spend cap stops all calls with `402 monthly_cap_reached`, and alerts fire at 50%, 80% and 100% of any cap. The [keys reference](/docs/keys) lists each field.

## Two worked examples with costs

Account mapping for 40 named accounts. The agent calls `dizo_best_contact` with the 40 domains and a ranked title list such as CFO, then VP Finance, then Controller. Assume it finds a person at all 40: that is 40 people at 1 credit per 25, or 1.6 credits. It then calls the email finder for each. Assume 34 emails are found and 6 are not; the misses are free, so that step costs 34 credits. The run totals 35.6 credits, about $0.89 at the $0.025 pay-as-you-go rate.

Inbound enrichment on a schedule. A product team runs the agent nightly over new signups, calling `dizo_email_to_profile` at 2 credits per profile found and returning a typed lead record. With 300 signups in a month and 240 matched, the month costs 480 credits. That is $12.00 at $0.025, or $10.08 if the credits came from a $500 to $1,999 purchase at $0.021. Unmatched addresses cost nothing, so a quiet month costs less. Current rates are on the [pricing page](/pricing).

## Validating what comes back

The value of Pydantic AI here is in the last step. Define an output model for the records you want, for example a list of contacts with name, title, company domain, email and the email's `status` and `confidence`, and have the agent return that type. If the model tries to return a row without a required field, validation fails and you find out before the data moves on.

Make missing data explicit rather than invented. Mark email as optional in the model and instruct the agent to leave it empty when `dizo_find_email` finds nothing, instead of guessing a pattern. Because Dizo does not charge for misses, there is no cost reason for the agent to try variations. If an email Dizo returned later bounces, report it with `dizo_report_bad_data` or `POST /v1/feedback`; confirmed reports are credited back automatically.

## Troubleshooting

Here are the problems you are most likely to hit and how to read them:

- 401 or an auth error on connect: the key is missing or mistyped. Check that `DIZO_API_KEY` is set in the process that runs the agent, not just your shell.
- ValueError when loading the config: a `${VAR}` in `mcp_config.json` is not set. Export it or fix the name.
- Tools missing from the agent: confirm the toolset is in `toolsets=[...]` and that the key's endpoint allow-list includes the tools you expect.
- 402 `monthly_cap_reached`: the account cap is hit. Stop the run; raising the cap is a human decision.
- Per-call limit errors on large jobs: the 500-credit MCP default blocked the call. Split the job, or raise the key's limit deliberately.
- Rate limit responses: branch on `error.retryable` and wait `error.retry_after` seconds before retrying.

## Security practices for production agents

Read the key from the environment or a secrets manager, never from source. Give each deployed agent its own key so you can see its usage separately with `dizo_balance` and revoke it without touching anything else. Keep billing scopes off agent keys: only a key with `billing:write` can top up or change refills, and the account owner can lock billing entirely.

Run development and CI against a `dz_test_` key so tests never spend credits, and switch to a live key only in the deployed environment. For broader guidance on how autonomous callers should behave, including idempotency and error handling, see the [agent instructions](/agents). To get a live key, [sign up](/signup); new accounts receive 250 free credits.

## FAQ

### Which Pydantic AI class connects to Dizo?
`MCPToolset` from `pydantic_ai.mcp`. Pass `https://mcp.dizo.ai/mcp` as the URL and your key as `auth`, then add the toolset to `Agent(toolsets=[...])`. Install it with `pip install "pydantic-ai-slim[mcp]"`.

### Do I need async with agent before every run?
No. The toolset opens and closes its connection automatically on each run. Use `async with agent:` only when you want several runs to share one connection.

### Can I use OAuth instead of an API key?
Dizo supports OAuth 2.1 for MCP clients, and Pydantic AI's docs list an `'oauth'` option for `auth`. For server-side agents a scoped API key is usually simpler, because you can set its caps and allow-list directly.

### How do I stop the agent from overspending?
Put quoting rules in the agent's instructions, then enforce limits on the key: `max_credits_per_request`, daily and monthly caps and an endpoint allow-list. The account-wide monthly cap returns `402 monthly_cap_reached` when hit.

### Does the agent pay when a lookup finds nothing?
No. Email, phone and profile lookups that return nothing are free, and searches charge only for results returned. Counts and the account tools are always free.

### Is there a native Dizo package for Pydantic AI?
No. You connect through Pydantic AI's standard MCP support to the hosted Dizo server. You can also call the REST API at `https://api.dizo.ai/v1` from your own function tools if you need behaviour MCP does not cover.
