# How to integrate Imgix MCP with OpenAI Agents SDK

```json
{
  "title": "How to integrate Imgix MCP with OpenAI Agents SDK",
  "toolkit": "Imgix",
  "toolkit_slug": "imgix",
  "framework": "OpenAI Agents SDK",
  "framework_slug": "open-ai-agents-sdk",
  "url": "https://composio.dev/toolkits/imgix/framework/open-ai-agents-sdk",
  "markdown_url": "https://composio.dev/toolkits/imgix/framework/open-ai-agents-sdk.md",
  "updated_at": "2026-05-12T10:15:51.180Z"
}
```

## Introduction

This guide walks you through connecting Imgix to the OpenAI Agents SDK using the Composio tool router. By the end, you'll have a working Imgix agent that can auto-optimize all images in this folder, overlay company logo on product photos, extract main color palette from image through natural language commands.
This guide will help you understand how to give your OpenAI Agents SDK agent real control over a Imgix account through Composio's Imgix MCP server.
Before we dive in, let's take a quick look at the key ideas and tools involved.

## Also integrate Imgix with

- [Claude Agent SDK](https://composio.dev/toolkits/imgix/framework/claude-agents-sdk)
- [Claude Code](https://composio.dev/toolkits/imgix/framework/claude-code)
- [Claude Cowork](https://composio.dev/toolkits/imgix/framework/claude-cowork)
- [Codex](https://composio.dev/toolkits/imgix/framework/codex)
- [OpenClaw](https://composio.dev/toolkits/imgix/framework/openclaw)
- [Hermes](https://composio.dev/toolkits/imgix/framework/hermes-agent)
- [CLI](https://composio.dev/toolkits/imgix/framework/cli)
- [Google ADK](https://composio.dev/toolkits/imgix/framework/google-adk)
- [LangChain](https://composio.dev/toolkits/imgix/framework/langchain)
- [Vercel AI SDK](https://composio.dev/toolkits/imgix/framework/ai-sdk)
- [Mastra AI](https://composio.dev/toolkits/imgix/framework/mastra-ai)
- [LlamaIndex](https://composio.dev/toolkits/imgix/framework/llama-index)
- [CrewAI](https://composio.dev/toolkits/imgix/framework/crew-ai)

## TL;DR

Here's what you'll learn:
- Get and set up your OpenAI and Composio API keys
- Install the necessary dependencies
- Initialize Composio and create a Tool Router session for Imgix
- Configure an AI agent that can use Imgix as a tool
- Run a live chat session where you can ask the agent to perform Imgix operations

## What is OpenAI Agents SDK?

The OpenAI Agents SDK is a lightweight framework for building AI agents that can use tools and maintain conversation state. It provides a simple interface for creating agents with hosted MCP tool support.
Key features include:
- Hosted MCP Tools: Connect to external services through hosted MCP endpoints
- SQLite Sessions: Persist conversation history across interactions
- Simple API: Clean interface with Agent, Runner, and tool configuration
- Streaming Support: Real-time response streaming for interactive applications

## What is the Imgix MCP server, and what's possible with it?

The Imgix MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Imgix account. It provides structured and secure access to your image library, so your agent can perform actions like optimizing images, applying overlays, adjusting visual properties, and extracting color palettes on your behalf.
- Real-time image optimization: Ask your agent to automatically compress, enhance, or format images for faster delivery and better quality using Imgix's auto optimization tools.
- Dynamic overlays and blending: Direct the agent to blend images, text, or solid colors over your base images—perfect for watermarks, banners, or creative composites.
- Precision image adjustments: Have your agent modify image brightness, contrast, and border settings to meet your design and branding needs instantly.
- Extract and analyze color palettes: Let your agent pull color palettes from any image, making it easy to generate theme colors or analyze brand consistency.
- Fine-tune overlay positioning: Control exactly where overlays appear on your images by specifying alignment and pixel-level positioning through your agent.

## Supported Tools

| Tool slug | Name | Description |
|---|---|---|
| `IMGIX_ADD_ASSET_FROM_ORIGIN` | IMGIX_ADD_ASSET_FROM_ORIGIN | Tool to queue a path from your origin to be added to the Asset Manager. Imports the asset metadata without uploading the asset itself. Use when you need to register an existing origin-hosted file with imgix. |
| `IMGIX_AUTO` | Imgix Auto Optimization | Apply automatic image optimizations using imgix's auto parameter. Use this tool to automatically optimize images for web delivery. Common use cases: - Reduce file sizes with 'compress' for faster page loads - Auto-select modern formats (AVIF/WebP) with 'format' based on browser support - Enhance image quality with 'enhance' (adjusts brightness, contrast, saturation) - Remove red-eye from portrait photos with 'redeye' Multiple options can be combined (e.g., ['compress', 'format']) for cumulative optimizations. The 'true' option is a convenient shorthand that applies 'enhance' automatically. Note: This tool works with the imgix Rendering API and requires a valid imgix source domain. For testing, use 'assets.imgix.net' with paths like 'examples/kingfisher.jpg'. |
| `IMGIX_BLEND` | Blend Overlay | Tool to overlay an image, text, or color onto a base image using imgix blending parameters. Use after specifying the base image URL and blend parameters to composite layers. |
| `IMGIX_BLEND_ALIGN` | Imgix Blend Align | Tool to align the overlay relative to the base image when blending. Use after constructing a base Imgix URL to specify horizontal and vertical alignment (e.g., 'left,top'). |
| `IMGIX_BLEND_COLOR` | Blend Color Over Image | Tool to blend a solid color over an image using CSS keyword or hex. Use when you need to apply color overlay transformations to an existing image URL. |
| `IMGIX_BLEND_X` | Imgix Blend X Position | Position an overlay image horizontally on a base image using imgix's blend-x parameter. Use this tool when you need to place an overlay (image or color) at a specific horizontal offset from the left edge of the base image. This is useful for creating watermarks, badges, or composite images where precise positioning is required. Note: The blend-x parameter only affects image overlays. Color overlays always cover the entire image regardless of this setting. |
| `IMGIX_BORDER` | Draw Image Border | Tool to draw a border around an image. Use when you need to overlay a border without resizing. |
| `IMGIX_BRI` | Adjust Image Brightness | Tool to adjust image brightness. Use when you need to modify an image's brightness level (−100 to 100) by supplying your source domain and asset path. |
| `IMGIX_CANCEL_UPLOAD_SESSION` | IMGIX_CANCEL_UPLOAD_SESSION | Tool to cancel an Imgix Asset Manager upload session. Use when you need to abort an in-progress or abandoned upload flow and clean up the session. |
| `IMGIX_CH` | IMGIX_CH | Tool to opt in to Client Hints. Use when you want Imgix URLs to adapt based on browser headers (Width, DPR, Save-Data). |
| `IMGIX_CLOSE_UPLOAD_SESSION` | IMGIX_CLOSE_UPLOAD_SESSION | Tool to close an Imgix Asset Manager upload session after the client uploads to the presigned URL. Use after uploading a file to expedite asset processing. Closing is strongly recommended by imgix. |
| `IMGIX_CON` | Adjust Image Contrast | Tool to adjust image contrast. Use when you need to modify an image's contrast level (−100 to 100). |
| `IMGIX_CREATE_IMGIX_SOURCE` | IMGIX_CREATE_IMGIX_SOURCE | Tool to create and deploy a new imgix Source. Use when you need to add a new image source with deployment configuration for S3, Web Folder, Web Proxy, GCS, Azure, or S3-compatible storage. Requires source name and deployment details with type-specific credentials and settings. |
| `IMGIX_CREATE_UPLOAD_SESSION` | IMGIX_CREATE_UPLOAD_SESSION | Tool to create an Imgix Asset Manager upload session and return a presigned URL for client-side upload. Use when you need to upload a new image to a storage-backed imgix Source without requiring external hosting. Client performs HTTP PUT of file bytes to the presigned URL, then calls IMGIX_CLOSE_UPLOAD_SESSION to finalize. |
| `IMGIX_CS` | IMGIX_CS | Tool to set or strip output color space/profile on an Imgix image. Use when optimizing compatibility and file size (e.g., cs=strip for smaller metadata). |
| `IMGIX_DL` | IMGIX_DL | Download an asset from an Imgix source with optional custom filename. Use this tool when you need to: - Download images or assets from an Imgix CDN source - Force a specific download filename (via 'dl' parameter) - Download assets with special character filenames (via 'dl64' parameter) The asset is fetched from the Imgix CDN and returned as a downloadable file reference. If neither 'dl' nor 'dl64' is specified, the original filename from the path is used. |
| `IMGIX_DPI` | Adjust Image DPI | Tool to embed DPI (dots-per-inch) metadata for print output on an Imgix-rendered image. Use when preparing images for print to set accurate DPI. Supports JPEG and PNG only. |
| `IMGIX_DPR` | Set Device Pixel Ratio | Tool to set device pixel ratio for an Imgix image. Use when rendering at specific display densities to ensure correct sharpness. Example: 'dpr=2&w=500&h=300' doubles resolution relative to dimensions. |
| `IMGIX_EXPIRES` | Imgix URL Expiration | Tool to append an expiration parameter to an Imgix URL so it returns 404 after a given time. Use when you want the image URL to stop serving beyond a specific UNIX timestamp. |
| `IMGIX_FIT` | IMGIX_FIT | Tool to control how an image fits target dimensions after resizing. Use when specifying width, height, and fit behavior. |
| `IMGIX_FM` | IMGIX_FM | Tool to choose output file format for the rendered asset. Use after specifying the asset path when you need to convert its format. |
| `IMGIX_FORCE_ASPECT_RATIO` | Force Aspect Ratio | Tool to force a target aspect ratio on an Imgix image. Use when a specific W:H frame is needed after choosing fit=crop or fit=fill. Example: 'ar=16:9&fit=crop&w=800' yields a 16:9, 800px-wide URL. |
| `IMGIX_GET_SOURCE` | IMGIX_GET_SOURCE | Tool to retrieve details for a single imgix Source by its ID. Returns the source configuration including deployment status, type, and settings. |
| `IMGIX_GET_UPLOAD_SESSION_STATUS` | IMGIX_GET_UPLOAD_SESSION_STATUS | Tool to retrieve the status of an Imgix Asset Manager upload session. Use when you need to check the current state (PENDING/CLOSED/COMPLETE/CANCELED) of an upload session for polling or verification after client PUT and/or after closing. |
| `IMGIX_H` | IMGIX_H | Tool to set output image height in pixels or as a ratio of the source height. Use after constructing an Imgix URL to adjust only height. |
| `IMGIX_HIGH` | Adjust Image Highlights | Tool to adjust highlight tonal mapping (−100 to 0). Use when preserving detail in bright areas of an image. |
| `IMGIX_LIST_ASSETS` | IMGIX_LIST_ASSETS | Tool to retrieve a paginated list of assets in an imgix Source. Use when you need to list, filter, or search assets with cursor-based pagination and sorting. |
| `IMGIX_LIST_REPORTS` | IMGIX_LIST_REPORTS | Tool to retrieve a list of all available reports for your imgix account. Use when you need to access analytics and usage information. Reports are generated daily and retained for 90 days. |
| `IMGIX_LIST_SOURCES` | IMGIX_LIST_SOURCES | Tool to list all Sources for an account. Use when you need to retrieve and paginate through sources with optional sorting and filtering. |
| `IMGIX_MARK_BASE` | Set Watermark Base URL | Tool to set the base URL prepended to the watermark image path. Use when you need to host watermark assets on a custom domain or CDN. |
| `IMGIX_MARK_FIT` | Watermark Fit Mode | Tool to set how a watermark fits its target dimensions. Use when applying a watermark and you need control over fitting behavior (e.g., selecting 'scale'). For 'crop', ensure 'mark-w' and 'mark-h' are also provided. |
| `IMGIX_MARK_H` | Imgix Mark Height | Tool to set watermark height on an Imgix URL in pixels or as a ratio of the watermark source. Use when adjusting overlay height while preserving aspect ratio. |
| `IMGIX_MARK_PAD` | IMGIX_MARK_PAD | Tool to set pixel padding between a watermark and the image edge or between tiled watermarks. Use after configuring watermark URL and alignment to adjust spacing precisely. |
| `IMGIX_MARK_W` | Watermark Width | Tool to set watermark width. Use when you need to enforce a watermark's width in pixels or as a proportion. Use after specifying watermark source. |
| `IMGIX_MASK` | IMGIX_MASK | Tool to apply a mask to an image. Use when needing rounded corners, ellipse shapes, or image-based masks. |
| `IMGIX_MAX_H` | IMGIX_MAX_H | Constrain the maximum height of an imgix image. This tool applies fit=crop along with the max-h parameter to ensure images do not exceed the specified height. Ideal for vertically-scrolling feeds or galleries where user-uploaded images may have unpredictable heights. Returns a downloadable image URL. |
| `IMGIX_MAX_W` | IMGIX_MAX_W | Tool to set the maximum output width on an Imgix URL. Use when you need to cap width (works only with fit=crop). Call after specifying fit=crop on the URL. |
| `IMGIX_PALETTE` | IMGIX_PALETTE | Tool to extract a color palette from an image in CSS or JSON form. Use when you need to analyze an image's dominant colors after any transformations. |
| `IMGIX_PREFIX` | Set CSS Palette Prefix | Tool to set class-name prefix for CSS palette output. Use when customizing CSS selectors for color-palette styling. |
| `IMGIX_PURGE_IMGIX_ASSET` | IMGIX_PURGE_ASSET | Tool to purge an asset from the imgix cache. Use when you need to invalidate cached versions of an image and force imgix to fetch a fresh version from origin on the next request. |
| `IMGIX_Q` | Set Output Quality | Tool to set output quality for lossy formats. Use when adjusting image compression quality for lossy image delivery. |
| `IMGIX_RECT` | IMGIX_RECT | Tool to select a source-image rectangle region in Imgix before other resizing. Use when you need to crop a specific region (x,y,w,h) of the source image. |
| `IMGIX_ROT` | Imgix Rotate | Tool to rotate an image on Imgix. Use when you need to apply a counter-clockwise rotation (0–359°) with optional mode control. |
| `IMGIX_ROT_TYPE` | IMGIX_ROT_TYPE | Tool to control rotation behavior when `rot` is applied. Use after applying a `rot` parameter to choose between pivot (show entire image) or straighten (zoom and crop) behavior. |
| `IMGIX_TXT` | Text Overlay | Tool to render a single-line UTF-8 text overlay on an image. Use when you need simple text captions. |
| `IMGIX_TXT_ALIGN` | IMGIX_TXT_ALIGN | Tool to align a text overlay on an Imgix image. Use when you need to position text by specifying vertical (top/middle/bottom) and horizontal (left/center/right) alignment. |
| `IMGIX_TXT_COLOR` | Set Text Color | Tool to set text overlay color on an Imgix image. Use when customizing text overlays with CSS color keywords or hex codes. |
| `IMGIX_TXT_FONT` | Set Text Font | Tool to choose font family/style for overlay text. Use when customizing text appearance after specifying content. Supports CSS font categories and optional bold/italic flags. |
| `IMGIX_TXT_LINE` | Set Text Outline Width | Tool to set outline width around overlay text. Use when styling text overlays on images. |
| `IMGIX_TXT_LINE_COLOR` | Text Outline Color | Apply an outline color to text overlays on Imgix images. The text outline must first be enabled using the txt-line parameter (outline width > 0). This action fetches and returns the rendered image with the specified outline color applied. |
| `IMGIX_TXT_SHAD` | IMGIX_TXT_SHAD | Set text shadow strength for imgix text overlays. The txt-shad parameter controls the drop shadow intensity (0-10) applied to text rendered on images. Note: This parameter only has a visible effect when combined with text overlay parameters (e.g., txt parameter). Use this action to add depth and visibility to text overlays on images. |
| `IMGIX_TXT_SIZE` | IMGIX_TXT_SIZE | Tool to set text font size in pixels. Use when overlaying text and needing precise control over font size. Specify after defining the text content; default is 12px. |
| `IMGIX_UPDATE_SOURCE` | IMGIX_UPDATE_SOURCE | Tool to update an existing imgix Source. Use when you need to modify source name, deployment configuration, bucket settings, or other source attributes. Deployment changes trigger automatic redeployment. |

## Supported Triggers

None listed.

## Creating MCP Server - Stand-alone vs Composio SDK

The Imgix MCP server is an implementation of the Model Context Protocol that connects your AI agent to Imgix. It provides structured and secure access so your agent can perform Imgix operations on your behalf through a secure, permission-based interface.
With Composio's managed implementation, you don't have to create your own developer app. For production, if you're building an end product, we recommend using your own credentials. The managed server helps you prototype fast and go from 0-1 faster.

## Step-by-step Guide

### 1. Prerequisites

Before starting, make sure you have:
- Composio API Key and OpenAI API Key
- Primary know-how of OpenAI Agents SDK
- A live Imgix project
- Some knowledge of Python or Typescript

### 1. Getting API Keys for OpenAI and Composio

OpenAI API Key
- Go to the [OpenAI dashboard](https://platform.openai.com/settings/organization/api-keys) and create an API key. You'll need credits to use the models, or you can connect to another model provider.
- Keep the API key safe.
Composio API Key
- Log in to the [Composio dashboard](https://dashboard.composio.dev?utm_source=toolkits&utm_medium=framework_docs).
- Go to Settings and copy your API key.

### 2. Install dependencies

Install the Composio SDK and the OpenAI Agents SDK.
```python
pip install composio_openai_agents openai-agents python-dotenv
```

```typescript
npm install @composio/openai-agents @openai/agents dotenv
```

### 3. Set up environment variables

Create a .env file and add your OpenAI and Composio API keys.
```bash
OPENAI_API_KEY=sk-...your-api-key
COMPOSIO_API_KEY=your-api-key
USER_ID=composio_user@gmail.com
```

### 4. Import dependencies

What's happening:
- You're importing all necessary libraries.
- The Composio and OpenAIAgentsProvider classes are imported to connect your OpenAI agent to Composio tools like Imgix.
```python
import asyncio
import os
from dotenv import load_dotenv

from composio import Composio
from composio_openai_agents import OpenAIAgentsProvider
from agents import Agent, Runner, HostedMCPTool, SQLiteSession
```

```typescript
import 'dotenv/config';
import { Composio } from '@composio/core';
import { OpenAIAgentsProvider } from '@composio/openai-agents';
import { Agent, hostedMcpTool, run, OpenAIConversationsSession } from '@openai/agents';
import * as readline from 'readline';
```

### 5. Set up the Composio instance

No description provided.
```python
load_dotenv()

api_key = os.getenv("COMPOSIO_API_KEY")
user_id = os.getenv("USER_ID")

if not api_key:
    raise RuntimeError("COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key")

# Initialize Composio
composio = Composio(api_key=api_key, provider=OpenAIAgentsProvider())
```

```typescript
dotenv.config();

const composioApiKey = process.env.COMPOSIO_API_KEY;
const userId = process.env.USER_ID;

if (!composioApiKey) {
  throw new Error('COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key');
}
if (!userId) {
  throw new Error('USER_ID is not set');
}

// Initialize Composio
const composio = new Composio({
  apiKey: composioApiKey,
  provider: new OpenAIAgentsProvider(),
});
```

### 6. Create a Tool Router session

What is happening:
- You give the Tool Router the user id and the toolkits you want available. Here, it is only imgix.
- The router checks the user's Imgix connection and prepares the MCP endpoint.
- The returned session.mcp.url is the MCP URL that your agent will use to access Imgix.
- This approach keeps things lightweight and lets the agent request Imgix tools only when needed during the conversation.
```python
# Create a Imgix Tool Router session
session = composio.create(
    user_id=user_id,
    toolkits=["imgix"]
)

mcp_url = session.mcp.url
```

```typescript
// Create Tool Router session for Imgix
const session = await composio.create(userId as string, {
  toolkits: ['imgix'],
});
const mcpUrl = session.mcp.url;
```

### 7. Configure the agent

No description provided.
```python
# Configure agent with MCP tool
agent = Agent(
    name="Assistant",
    model="gpt-5",
    instructions=(
        "You are a helpful assistant that can access Imgix. "
        "Help users perform Imgix operations through natural language."
    ),
    tools=[
        HostedMCPTool(
            tool_config={
                "type": "mcp",
                "server_label": "tool_router",
                "server_url": mcp_url,
                "headers": {"x-api-key": api_key},
                "require_approval": "never",
            }
        )
    ],
)
```

```typescript
// Configure agent with MCP tool
const agent = new Agent({
  name: 'Assistant',
  model: 'gpt-5',
  instructions:
    'You are a helpful assistant that can access Imgix. Help users perform Imgix operations through natural language.',
  tools: [
    hostedMcpTool({
      serverLabel: 'tool_router',
      serverUrl: mcpUrl,
      headers: { 'x-api-key': composioApiKey },
      requireApproval: 'never',
    }),
  ],
});
```

### 8. Start chat loop and handle conversation

No description provided.
```python
print("\nComposio Tool Router session created.")

chat_session = SQLiteSession("conversation_openai_toolrouter")

print("\nChat started. Type your requests below.")
print("Commands: 'exit', 'quit', or 'q' to end\n")

async def main():
    try:
        result = await Runner.run(
            agent,
            "What can you help me with?",
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")
    except Exception as e:
        print(f"Error: {e}\n")

    while True:
        user_input = input("You: ").strip()
        if user_input.lower() in {"exit", "quit", "q"}:
            print("Goodbye!")
            break

        result = await Runner.run(
            agent,
            user_input,
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")

asyncio.run(main())
```

```typescript
// Keep conversation state across turns
const conversationSession = new OpenAIConversationsSession();

// Simple CLI
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  prompt: 'You: ',
});

console.log('\nComposio Tool Router session created.');
console.log('\nChat started. Type your requests below.');
console.log("Commands: 'exit', 'quit', or 'q' to end\n");

try {
  const first = await run(agent, 'What can you help me with?', { session: conversationSession });
  console.log(`Assistant: ${first.finalOutput}\n`);
} catch (e) {
  console.error('Error:', e instanceof Error ? e.message : e, '\n');
}

rl.prompt();

rl.on('line', async (userInput) => {
  const text = userInput.trim();

  if (['exit', 'quit', 'q'].includes(text.toLowerCase())) {
    console.log('Goodbye!');
    rl.close();
    process.exit(0);
  }

  if (!text) {
    rl.prompt();
    return;
  }

  try {
    const result = await run(agent, text, { session: conversationSession });
    console.log(`\nAssistant: ${result.finalOutput}\n`);
  } catch (e) {
    console.error('Error:', e instanceof Error ? e.message : e, '\n');
  }

  rl.prompt();
});

rl.on('close', () => {
  console.log('\n👋 Session ended.');
  process.exit(0);
});
```

## Complete Code

```python
import asyncio
import os
from dotenv import load_dotenv

from composio import Composio
from composio_openai_agents import OpenAIAgentsProvider
from agents import Agent, Runner, HostedMCPTool, SQLiteSession

load_dotenv()

api_key = os.getenv("COMPOSIO_API_KEY")
user_id = os.getenv("USER_ID")

if not api_key:
    raise RuntimeError("COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key")

# Initialize Composio
composio = Composio(api_key=api_key, provider=OpenAIAgentsProvider())

# Create Tool Router session
session = composio.create(
    user_id=user_id,
    toolkits=["imgix"]
)
mcp_url = session.mcp.url

# Configure agent with MCP tool
agent = Agent(
    name="Assistant",
    model="gpt-5",
    instructions=(
        "You are a helpful assistant that can access Imgix. "
        "Help users perform Imgix operations through natural language."
    ),
    tools=[
        HostedMCPTool(
            tool_config={
                "type": "mcp",
                "server_label": "tool_router",
                "server_url": mcp_url,
                "headers": {"x-api-key": api_key},
                "require_approval": "never",
            }
        )
    ],
)

print("\nComposio Tool Router session created.")

chat_session = SQLiteSession("conversation_openai_toolrouter")

print("\nChat started. Type your requests below.")
print("Commands: 'exit', 'quit', or 'q' to end\n")

async def main():
    try:
        result = await Runner.run(
            agent,
            "What can you help me with?",
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")
    except Exception as e:
        print(f"Error: {e}\n")

    while True:
        user_input = input("You: ").strip()
        if user_input.lower() in {"exit", "quit", "q"}:
            print("Goodbye!")
            break

        result = await Runner.run(
            agent,
            user_input,
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")

asyncio.run(main())
```

```typescript
import 'dotenv/config';
import { Composio } from '@composio/core';
import { OpenAIAgentsProvider } from '@composio/openai-agents';
import { Agent, hostedMcpTool, run, OpenAIConversationsSession } from '@openai/agents';
import * as readline from 'readline';

const composioApiKey = process.env.COMPOSIO_API_KEY;
const userId = process.env.USER_ID;

if (!composioApiKey) {
  throw new Error('COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key');
}
if (!userId) {
  throw new Error('USER_ID is not set');
}

// Initialize Composio
const composio = new Composio({
  apiKey: composioApiKey,
  provider: new OpenAIAgentsProvider(),
});

async function main() {
  // Create Tool Router session
  const session = await composio.create(userId as string, {
    toolkits: ['imgix'],
  });
  const mcpUrl = session.mcp.url;

  // Configure agent with MCP tool
  const agent = new Agent({
    name: 'Assistant',
    model: 'gpt-5',
    instructions:
      'You are a helpful assistant that can access Imgix. Help users perform Imgix operations through natural language.',
    tools: [
      hostedMcpTool({
        serverLabel: 'tool_router',
        serverUrl: mcpUrl,
        headers: { 'x-api-key': composioApiKey },
        requireApproval: 'never',
      }),
    ],
  });

  // Keep conversation state across turns
  const conversationSession = new OpenAIConversationsSession();

  // Simple CLI
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    prompt: 'You: ',
  });

  console.log('\nComposio Tool Router session created.');
  console.log('\nChat started. Type your requests below.');
  console.log("Commands: 'exit', 'quit', or 'q' to end\n");

  try {
    const first = await run(agent, 'What can you help me with?', { session: conversationSession });
    console.log(`Assistant: ${first.finalOutput}\n`);
  } catch (e) {
    console.error('Error:', e instanceof Error ? e.message : e, '\n');
  }

  rl.prompt();

  rl.on('line', async (userInput) => {
    const text = userInput.trim();

    if (['exit', 'quit', 'q'].includes(text.toLowerCase())) {
      console.log('Goodbye!');
      rl.close();
      process.exit(0);
    }

    if (!text) {
      rl.prompt();
      return;
    }

    try {
      const result = await run(agent, text, { session: conversationSession });
      console.log(`\nAssistant: ${result.finalOutput}\n`);
    } catch (e) {
      console.error('Error:', e instanceof Error ? e.message : e, '\n');
    }

    rl.prompt();
  });

  rl.on('close', () => {
    console.log('\nSession ended.');
    process.exit(0);
  });
}

main().catch((err) => {
  console.error('Fatal error:', err);
  process.exit(1);
});
```

## Conclusion

This was a starter code for integrating Imgix MCP with OpenAI Agents SDK to build a functional AI agent that can interact with Imgix.
Key features:
- Hosted MCP tool integration through Composio's Tool Router
- SQLite session persistence for conversation history
- Simple async chat loop for interactive testing
You can extend this by adding more toolkits, implementing custom business logic, or building a web interface around the agent.

## How to build Imgix MCP Agent with another framework

- [Claude Agent SDK](https://composio.dev/toolkits/imgix/framework/claude-agents-sdk)
- [Claude Code](https://composio.dev/toolkits/imgix/framework/claude-code)
- [Claude Cowork](https://composio.dev/toolkits/imgix/framework/claude-cowork)
- [Codex](https://composio.dev/toolkits/imgix/framework/codex)
- [OpenClaw](https://composio.dev/toolkits/imgix/framework/openclaw)
- [Hermes](https://composio.dev/toolkits/imgix/framework/hermes-agent)
- [CLI](https://composio.dev/toolkits/imgix/framework/cli)
- [Google ADK](https://composio.dev/toolkits/imgix/framework/google-adk)
- [LangChain](https://composio.dev/toolkits/imgix/framework/langchain)
- [Vercel AI SDK](https://composio.dev/toolkits/imgix/framework/ai-sdk)
- [Mastra AI](https://composio.dev/toolkits/imgix/framework/mastra-ai)
- [LlamaIndex](https://composio.dev/toolkits/imgix/framework/llama-index)
- [CrewAI](https://composio.dev/toolkits/imgix/framework/crew-ai)

## Related Toolkits

- [Figma](https://composio.dev/toolkits/figma) - Figma is a collaborative interface design tool for teams and individuals. It streamlines design workflows with real-time collaboration and easy sharing.
- [Abyssale](https://composio.dev/toolkits/abyssale) - Abyssale is a creative automation platform for generating images, videos, GIFs, PDFs, and HTML5 content programmatically. It streamlines and scales visual content production for marketing, design, and operations teams.
- [Alttext ai](https://composio.dev/toolkits/alttext_ai) - AltText.ai is a service that generates alt text for images automatically. It helps boost accessibility and SEO for your visual content.
- [Bannerbear](https://composio.dev/toolkits/bannerbear) - Bannerbear is an API-driven platform for generating images and videos automatically at scale. It helps businesses create custom graphics, social visuals, and marketing assets using powerful templates.
- [Canva](https://composio.dev/toolkits/canva) - Canva is a drag-and-drop design suite for creating professional graphics, presentations, and marketing materials. It makes it easy for anyone to design with beautiful templates and a vast library of elements.
- [Claid ai](https://composio.dev/toolkits/claid_ai) - Claid.ai delivers AI-driven image editing APIs for tasks like background removal, upscaling, and color correction. It helps automate and enhance image workflows with powerful, developer-friendly tools.
- [Cloudinary](https://composio.dev/toolkits/cloudinary) - Cloudinary is a cloud-based platform for managing, uploading, and transforming images and videos. It streamlines media workflows and delivers optimized assets globally.
- [Cults](https://composio.dev/toolkits/cults) - Cults is a digital marketplace for 3D printing models, connecting designers and makers. It lets creators share, sell, and discover a huge variety of printable designs easily.
- [DeepImage](https://composio.dev/toolkits/deepimage) - DeepImage is an AI-powered image enhancer and upscaler. Get higher-quality images with just a few clicks.
- [Dreamstudio](https://composio.dev/toolkits/dreamstudio) - DreamStudio is Stability AI’s platform for generating and editing images with AI. It lets you easily turn ideas into stunning visuals, fast.
- [Dynapictures](https://composio.dev/toolkits/dynapictures) - Dynapictures is a cloud-based platform for generating personalized images at scale. Instantly create hundreds of custom visuals using your data sources, like Google Sheets.
- [Fal.ai](https://composio.dev/toolkits/fal_ai) - Fal.ai is a generative media platform offering 600+ AI models for images, video, voice, and audio. Developers use Fal.ai for fast, scalable access to cutting-edge generative AI tools.
- [Gamma](https://composio.dev/toolkits/gamma) - Gamma is an AI-powered platform for making beautiful, interactive presentations and documents. It lets anyone create and share engaging decks with minimal effort.
- [Html to image](https://composio.dev/toolkits/html_to_image) - Html to image converts HTML and CSS into images or captures web page screenshots. Instantly generate visuals from code or web content—no manual screenshots needed.
- [Imagior](https://composio.dev/toolkits/imagior) - Imagior is an AI-powered image generation platform that lets you create and customize images using dynamic templates and APIs. Perfect for businesses and creators needing fast, scalable visuals without design hassle.
- [Imejis io](https://composio.dev/toolkits/imejis_io) - Imejis io is an API-based image generation platform with powerful customization and template support. It lets you create and modify images in seconds, no manual design work required.
- [Kraken io](https://composio.dev/toolkits/kraken_io) - Kraken.io is an image optimization and compression platform. It helps you shrink image file sizes while keeping visual quality intact.
- [Logo dev](https://composio.dev/toolkits/logo_dev) - Logo.dev is an API and database for high-resolution company logos and brand metadata. Instantly fetch official logos from any domain without scraping or manual searching.
- [Miro](https://composio.dev/toolkits/miro) - Miro is a collaborative online whiteboard platform for teams to brainstorm, design, and manage projects visually. It streamlines teamwork by enabling real-time idea sharing, diagramming, and workflow planning in a single space.
- [Mural](https://composio.dev/toolkits/mural) - Mural is a digital whiteboard platform for distributed visual collaboration. It helps teams brainstorm, map ideas, and diagram together in real time.

## Frequently Asked Questions

### What are the differences in Tool Router MCP and Imgix MCP?

With a standalone Imgix MCP server, the agents and LLMs can only access a fixed set of Imgix tools tied to that server. However, with the Composio Tool Router, agents can dynamically load tools from Imgix and many other apps based on the task at hand, all through a single MCP endpoint.

### Can I use Tool Router MCP with OpenAI Agents SDK?

Yes, you can. OpenAI Agents SDK fully supports MCP integration. You get structured tool calling, message history handling, and model orchestration while Tool Router takes care of discovering and serving the right Imgix tools.

### Can I manage the permissions and scopes for Imgix while using Tool Router?

Yes, absolutely. You can configure which Imgix scopes and actions are allowed when connecting your account to Composio. You can also bring your own OAuth credentials or API configuration so you keep full control over what the agent can do.

### How safe is my data with Composio Tool Router?

All sensitive data such as tokens, keys, and configuration is fully encrypted at rest and in transit. Composio is SOC 2 Type 2 compliant and follows strict security practices so your Imgix data and credentials are handled as safely as possible.

---
[See all toolkits](https://composio.dev/toolkits) · [Composio docs](https://docs.composio.dev/llms.txt)
