# Cloudflare Agents + Dizo

> Connect a Cloudflare Agent to Dizo with addMcpServer and a bearer header, then hand this.mcp.getAITools() to the AI SDK.

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

## Steps
1. In your Workers project with the `agents` package, store the key as a secret: `npx wrangler secret put DIZO_API_KEY`.
2. In the agent's `onStart()`, call `this.addMcpServer("dizo", url, { transport: { type: "streamable-http", headers } })`. It is safe to call on every wake.
3. Pass `this.mcp.getAITools()` as `tools` to `generateText` or `streamText` from the AI SDK.
4. If the token changes, call `reconnectMcpServer("dizo")`, or remove the server and add it again.

## Where to go
`addMcpServer()` for remote MCP servers, with custom headers.

Open the Cloudflare Agents MCP docs: https://developers.cloudflare.com/agents/model-context-protocol/apis/client-api/#adding-mcp-servers

## src/agent.ts
```
import { Agent } from "agents";
import { generateText } from "ai";
import { createAI } from "agents/models/ai-sdk";

interface Env { AI: Ai; DIZO_API_KEY: string }

export class Prospector extends Agent<Env> {
  async onStart() {
    await this.addMcpServer("dizo", "https://mcp.dizo.ai/mcp", {
      id: "dizo",
      transport: {
        type: "streamable-http",
        headers: { Authorization: `Bearer ${this.env.DIZO_API_KEY}` },
      },
    });
  }

  async onRequest(request: Request) {
    const ai = createAI({ binding: this.env.AI });
    const { text } = await generateText({
      model: ai("@cf/zai-org/glm-4.7-flash"),
      system: "Call dizo_whoami first. Quote with dizo_quote before jobs over 100 credits.",
      prompt: await request.text(),
      tools: this.mcp.getAITools(),
    });
    return new Response(text);
  }
}
```

## Notes
- Cloudflare stores MCP headers as plain text in the agent's Durable Object storage, so use a dedicated, capped Dizo key for each agent.
- A revoked or wrong key fails with a 401 and is not retried on a timer: fix the secret, then reconnect the server.
- The Workers AI model in the example comes from Cloudflare's docs; see the Agents docs for other model options.

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


## Cloudflare Agents, briefly

Cloudflare Agents is a TypeScript framework for building stateful agents on Workers. Each agent is a class that extends `Agent` from the `agents` package and runs on a Durable Object, so it keeps its own state, wakes on requests or schedules, and hibernates when idle. The framework includes a built-in MCP client: an agent can connect to remote MCP servers, keep those connections across hibernation, and expose the servers' tools to the AI SDK.

Dizo is a remote MCP server at `https://mcp.dizo.ai/mcp` using streamable HTTP. Connecting it with `addMcpServer` gives a Cloudflare Agent the full set of Dizo tools: plain-English and structured search, the decision-maker finder, org charts, email and phone finders, enrichment, reverse lookups, and free tools for counts, quotes and budget checks. Because the agent is long-lived, one connection serves every request the agent handles until you change it.

## Why pair a stateful edge agent with Dizo

Cloudflare Agents shine at work that spans time: an agent per account, per user or per deal that remembers what it did yesterday and runs on a schedule. Contact data fits that model well. An agent assigned to an account can map its buying committee once, store the results in its own state, and only call Dizo again when something changes. That keeps spend low, because Dizo charges per record returned and lookups that find nothing are free.

Dizo's controls also suit unattended agents. Every tool description carries its credit cost. `dizo_quote` returns the exact cost of a call and spends nothing. `dizo_whoami` reports the key's scopes, caps and remaining budget. Combined with per-key caps, that lets you run hundreds of small agents without any of them being able to run up a bill past the limit you set. The [agent rules](/agents) describe the patterns Dizo recommends.

There is a practical benefit to running at the edge as well. A form-enrichment or routing agent sits close to the user, makes one Dizo call, and answers before the page finishes loading. The agent keeps its MCP connection across requests, so each lookup reuses an existing session. That matters most for synchronous jobs such as lead routing, where a slow lookup means a lead waits in the wrong queue.

## Agent designs that work well

Some concrete patterns for Cloudflare Agents with Dizo tools:

- An account agent, one Durable Object per target domain, that calls `dizo_domain_to_company` and `dizo_org_chart` once and caches the results in state.
- A scheduled agent that runs a saved search each morning and stores only people it has not seen before. A Dizo [monitor](/docs/monitors) can do the diffing for you at 1 credit per 25 new results.
- A form-enrichment endpoint: the agent receives a signup email, calls `dizo_email_to_profile`, and returns title, seniority and company in a single request.
- A per-user research assistant where each signed-in user connects their own Dizo account through OAuth.
- A pre-send QA step that drops any phone flagged `dnc` and any contact on your suppression list before a campaign tool picks up the list.
- A webhook receiver for `dizo_watch_job_changes` events that updates the matching account agent's state.

## Connecting the server

Start from a Workers project that uses the `agents` package and the AI SDK. Store the Dizo key as a Worker secret with `npx wrangler secret put DIZO_API_KEY` so it reaches the agent as `this.env.DIZO_API_KEY` and never appears in source. Check Cloudflare's Agents getting-started guide for the Durable Object bindings your `wrangler` config needs.

In the agent's `onStart()` method, call `this.addMcpServer("dizo", "https://mcp.dizo.ai/mcp", options)`. The options object takes an optional `id`, which gives the connection a stable identifier, and a `transport` object with `type: "streamable-http"` and `headers` containing `Authorization: Bearer` plus the key. Cloudflare documents the call as idempotent, so running it on every wake is safe and does not create duplicate connections.

To use the tools, pass `this.mcp.getAITools()` as the `tools` option of `generateText` or `streamText`. That returns the connected servers' tools in the format the AI SDK expects. If you only want to inspect what Dizo exposes, `this.mcp.listTools()` returns the raw MCP tool records instead. After hibernation, `waitForConnections()` makes sure restored tools are available before you call the model.

## Static key or per-user OAuth

A static key in headers is the right choice when the agent works for your team, such as a scheduled list builder or an internal assistant. One key, one set of caps, one usage line in the Dizo console.

When each of your users should spend from their own Dizo account, use OAuth instead. Dizo supports OAuth 2.1 for MCP clients. Call `addMcpServer` without the header; if the server requires sign-in, the result has `state: "authenticating"` and an `authUrl`. Send the user to that URL, and once they approve, the connection becomes ready. OAuth connections to Dizo get the `data:read` scope and a 500-credit per-call limit by default, which the user can change in their own console.

## Spend controls and costs

Give each agent class its own key with `data:read` only, a `max_credits_per_request`, daily and monthly caps, and an endpoint allow-list. The [keys reference](/docs/keys) covers each field. Put spending rules in the model's system prompt too: call `dizo_whoami` first, size searches with the free `dizo_count`, and quote anything over about 100 credits.

Here is a worked example. An account agent maps a target domain once: domain to company is 1 credit if found, and the org chart returns, say, 40 people at 1 credit per 25 results, so 1.6 credits. It then finds emails for 5 chosen people, all found, for 5 credits. The first pass costs 7.6 credits, about $0.19 at the $0.025 pay-as-you-go rate. Run that across 200 accounts and you spend 1,520 credits, $38.00 at pay-as-you-go or $15.20 at the $0.010 top tier. Later visits read from state and cost nothing. See [pricing](/pricing) for every tier.

## Three end-to-end workflows

**Inbound enrichment at the edge.** Your signup form posts to a Worker that routes to a Cloudflare Agent. The agent calls `dizo_email_to_profile`, which costs 2 credits only if found, and returns a JSON object with the person's title, seniority and employer. The form handler uses it to route the lead. With a 60 percent match rate, 1,000 signups a month cost 1,200 credits, $30.00 at the entry rate.

**Daily new-executive watch.** A scheduled agent wakes each morning, asks Dizo for new VPs of Sales at fintech companies in a region, and compares results to the list in its state. Rather than diffing yourself, create a Dizo monitor with a webhook and a `max_credits_per_run`, and let the agent consume the webhook. Either way, the agent stores what it has seen so repeated mornings cost only for new people.

**Buying committee per account.** For account-based programs, create one agent per target domain. On first run it calls `dizo_best_contact` with a ranked list of titles, for example CFO, then VP Finance, then Controller, and records the person it gets back. At 1 credit per 25 people returned, picking one person at each of 500 accounts costs 20 credits. Email lookups for those 500 people at an 80 percent hit rate add 400 credits. The agent keeps the result in state and only refreshes when a job-change webhook says the contact moved.

## Troubleshooting

If the model never calls a Dizo tool, check that `addMcpServer` resolved with `state: "ready"` and that you passed `this.mcp.getAITools()` rather than the raw tool list. After hibernation, await `waitForConnections()` before generating. If the connection fails with a 401, the key is wrong or revoked. Cloudflare does not retry that on a timer: update the secret, then call `reconnectMcpServer("dizo")` or remove and re-add the server.

A `402` from Dizo means a cap or the balance was reached, and the error includes a plain-English `fix`. Rate limit errors include `error.retryable` and `error.retry_after`. Tell the model to respect them, or catch them in your own code and retry later with an alarm.

## Security practices

Cloudflare stores MCP headers as plain text in the Durable Object's storage, and restored connections resend them. Treat that as a reason to use a narrow key: one per agent class, `data:read` only, tight caps and an allow-list limited to the tools the agent uses. If a key leaks, revoke it in the Dizo console without affecting other agents.

Develop with a `dz_test_` key, which returns synthetic data and never spends credits. Only switch to a live key when the agent behaves the way you want. [Sign up](/signup) to get a live key.

## FAQ

### Which transport does Dizo use with Cloudflare Agents?
Streamable HTTP. Set `transport: { type: "streamable-http" }` in the `addMcpServer` options and include your bearer key in `transport.headers`.

### Is it safe to call addMcpServer on every wake?
Yes. Cloudflare documents the call as idempotent, so calling it in `onStart()` each time the agent wakes does not create duplicate connections.

### How do I give the Dizo tools to the model?
Pass `this.mcp.getAITools()` as the `tools` option of `generateText` or `streamText`. It returns the connected MCP tools in the AI SDK's format.

### Can each of my users connect their own Dizo account?
Yes. Dizo supports OAuth 2.1. Add the server without a header, and if the result is `authenticating`, send the user to the returned `authUrl`. OAuth connections default to `data:read` and a 500-credit per-call limit.

### What happens if my agent hits its Dizo budget?
Calls return a 402 with a plain-English `fix`, and nothing more is charged. Raise the cap in the console or wait for the next day or month, depending on which cap was reached.

### Do I pay for lookups that return nothing?
No. Email, phone and profile lookups are charged only when found, and searches only for results returned. Counts and dry-run quotes are free.
