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

# Build an agent with Cloudflare Agents

> Learn how to integrate ATXP's pay-per-use MCP tools with Cloudflare's Agent platform for building AI-powered chat agents

## Overview

Cloudflare Agents provides a platform for building AI-powered chat agents that run on Cloudflare's edge network. By combining Cloudflare Agents with ATXP's pay-per-use MCP tools, you can create AI applications that can generate images, search the web, crawl sites, and more - all with usage-based pricing and seamless deployment.

This guide will show you how to integrate ATXP's MCP tools with Cloudflare Agents to build a chat agent with image generation capabilities. You can find a full working example at [atxp-cloudflare-agent-example](https://github.com/atxp-dev/atxp-cloudflare-agent-example).

## Setup

<Steps>
  <Step title="Create ATXP account">
    <p>
      If you don't have an ATXP account yet, <a href="/developers/build-agents/create-account" target="_blank">create one</a> and copy your ATXP connection string. It should look something like this:

      ```bash theme={null}
      https://accounts.atxp.ai?connection_token=<random_string>
      ```
    </p>

    <Tip>
      If you've already created an ATXP account, you can visit the <a href="https://accounts.atxp.ai" target="_blank">ATXP account dashboard</a> to get your connection string.
    </Tip>
  </Step>

  <Step title="Create your project">
    Create a new Cloudflare Agent project:

    ```bash theme={null}
    npx create-cloudflare@latest --template cloudflare/agents-starter my-atxp-agent
    cd my-atxp-agent
    ```
  </Step>

  <Step title="Install ATXP client">
    Add the ATXP client to your project:

    ```bash theme={null}
    npm install @atxp/client
    ```

    <Info>
      The `@atxp/client` package provides the MCP transport that allows you to use ATXP's MCP tools in your Cloudflare Agent.
    </Info>
  </Step>

  <Step title="Configure environment">
    Create a `.dev.vars` file in your project root:

    ```bash theme={null}
    OPENAI_API_KEY=your_openai_api_key_here
    ATXP_CONNECTION_STRING=https://accounts.atxp.ai?connection_token=<your_token>
    ```

    <Warning>
      Never commit your `.dev.vars` file to version control. Make sure it's included in your `.gitignore` file.
    </Warning>
  </Step>
</Steps>

## Basic integration

Here's how to add ATXP image generation to your Cloudflare Agent:

<CodeGroup>
  ```typescript src/tools/imageGeneration.ts theme={null}
  import { tool } from "agents";
  import { z } from "zod";
  import { ATXPAccount, buildStreamableTransport, createMCPClient } from "@atxp/client";

  export const generateImage = tool({
    description: "Generate an image from a text prompt using ATXP",
    parameters: z.object({
      prompt: z.string().describe("The text prompt to generate an image from"),
    }),
    execute: async ({ prompt }, { env, agent }) => {
      try {
        // Initialize ATXP account
        const account = new ATXPAccount(env.ATXP_CONNECTION_STRING);

        // Create transport for ATXP image server
        const transport = buildStreamableTransport({
          mcpServer: 'https://image.mcp.atxp.ai',
          account,
        });

        // Create MCP client
        const client = await createMCPClient({ transport });

        // Generate the image
        const result = await client.callTool('generate_image', {
          prompt: prompt,
          size: '1024x1024'
        });

        if (result.toolResult.content[0].type === 'text') {
          const response = JSON.parse(result.toolResult.content[0].text);

          if (response.image_url) {
            return `Image generated successfully! Here's your image: ![${prompt}](${response.image_url})`;
          } else {
            return `Image generation started. Task ID: ${response.task_id}`;
          }
        }

        return "Image generation request submitted successfully.";
      } catch (error) {
        console.error('Image generation error:', error);
        return `Failed to generate image: ${error.message}`;
      }
    },
  });
  ```

  ```typescript src/tools.ts theme={null}
  import { generateImage } from "./tools/imageGeneration";

  export const tools = {
    generateImage,
    // ... other tools
  };

  export const executions = {
    // Add any tools that require confirmation here
  };
  ```

  ```typescript src/server.ts theme={null}
  import { createAgent } from "agents";
  import { tools, executions } from "./tools";

  export default {
    async fetch(request: Request, env: Env): Promise<Response> {
      const agent = createAgent({
        model: openai("gpt-4o-mini", {
          apiKey: env.OPENAI_API_KEY,
        }),
        tools,
        executions,
        // ... other configuration
      });

      return agent.fetch(request, { env });
    },
  };
  ```
</CodeGroup>

## Deploy your agent

<Steps>
  <Step title="Set production secrets">
    Configure your production environment variables:

    ```bash theme={null}
    wrangler secret put OPENAI_API_KEY
    wrangler secret put ATXP_CONNECTION_STRING
    ```
  </Step>

  <Step title="Deploy to Cloudflare">
    Deploy your agent:

    ```bash theme={null}
    npm run deploy
    ```

    Your agent will be available at your Cloudflare Workers subdomain.
  </Step>
</Steps>

## Test your agent

Once deployed, you can test your agent by asking it to generate images:

```
User: "Generate an image of a sunset over mountains"
Agent: "I'll generate an image of a sunset over mountains for you..."
[Image appears in the chat when complete]
```

## Next steps

Now that you have a working Cloudflare Agent with ATXP integration, you can explore more:

<CardGroup cols={3}>
  <Card title="MCP server documentation" icon="book" href="/tools">
    Learn about other ATXP tools like web search and file storage.
  </Card>

  <Card title="Build a CLI agent" icon="code" href="/developers/build-agents/tutorial">
    Try building a CLI agent.
  </Card>
</CardGroup>
