# API.Market MCP Server Guide

### Introduction

API.Market has revolutionized how AI agents interact with external APIs by implementing **Model Context Protocol (MCP)** servers for every API in our marketplace. This means that any API available on API.Market can be seamlessly integrated into AI agents like Claude, Cursor, and other MCP-compatible tools.

#### Why MCP Matters

Traditional API integration requires:

* Manual endpoint documentation reading
* Custom code for each API
* Complex authentication handling
* Error handling and retry logic
* Response parsing and formatting

With MCP, AI agents can:

* **Automatically discover** available API endpoints
* **Understand** parameter requirements and formats
* **Execute** API calls with proper authentication
* **Handle** responses intelligently
* **Chain** multiple API calls for complex workflows

***

### What is Model Context Protocol (MCP)?

Model Context Protocol is an open standard created by Anthropic that enables AI applications to securely access external data sources and tools. It provides a standardized way for AI models to:

#### Core Capabilities

* **Tool Discovery**: Automatically find and understand available functions
* **Resource Access**: Read and manipulate external data sources
* **Interactive Prompts**: Handle complex user interactions
* **Streaming**: Support real-time data flow
* **Security**: Implement proper authentication and authorization

#### Protocol Architecture

MCP uses JSON-RPC 2.0 over various transports:

* **HTTP/HTTPS**: For web-based integrations
* **Server-Sent Events (SSE)**: For real-time streaming
* **WebSockets**: For bidirectional communication
* **Stdio**: For local process communication

***

### API.Market MCP Implementation

#### Universal MCP Servers

**Every API on API.Market is automatically an MCP server**. This means:

* ✅ **Instant Integration**: No setup required beyond configuration
* ✅ **Automatic Updates**: API changes reflect immediately in MCP tools
* ✅ **Consistent Interface**: All APIs follow the same MCP patterns
* ✅ **Authentication Handled**: Your API key works across all MCP clients

#### Endpoint Pattern

All API.Market MCP servers follow this URL pattern:

```
https://prod.api.market/api/mcp/{workspace}/{api-slug}
```

**Examples**:

* `https://prod.api.market/api/mcp/magicapi/ideogram-v3-pro-text-to-image`
* `https://prod.api.market/api/mcp/magicapi/flux-8b-text-to-image`
* `https://prod.api.market/api/mcp/byteplus/seedance-image-to-video-pro`

#### Tool Generation

Each API endpoint becomes an MCP tool:

* **POST /images/generate** → `post_images_generate` tool
* **PUT /models/{id}** → `put_models_by_id` tool
* **GET /images/result** → `get_images_result` tool

#### Authentication

All MCP servers use the same authentication header:

```
x-api-market-key: YOUR_API_KEY
```

***

### Quick Start Guide

#### Prerequisites

* AI client that supports MCP (Claude Desktop, Cursor, etc.)
* Node.js 18+ (for most MCP clients)
* API.Market account with API key
* Active subscription to desired APIs

#### Step 1: Get Your API Key

1. Visit [API.Market](https://api.market)
2. Sign in to your account
3. Navigate to your dashboard
4. Copy your API key

#### Step 2: Choose Your Client

Pick your preferred MCP client:

* **Claude Desktop**: Best for conversational AI workflows
* **Cursor**: Ideal for code development with AI assistance
* **Python**: For programmatic access and automation
* **cURL**: For testing and debugging

#### Step 3: Configure MCP Server

Follow the client-specific configuration below.

***

### Client Configuration

#### Claude Desktop

**Configuration File Location**

* **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
* **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`

**Single API Configuration**

```json
{
  "mcpServers": {
    "ideogram_v3_pro": {
      "command": "npx",
      "args": [
        "-y",
        "mcp-remote",
        "https://prod.api.market/api/mcp/magicapi/ideogram-v3-pro-text-to-image",
        "--header",
        "x-api-market-key: ${API_MARKET_KEY}"
      ],
      "env": {
        "API_MARKET_KEY": "your_actual_api_key_here"
      }
    }
  }
}
```

**Multiple APIs Configuration**

```json
{
  "mcpServers": {
    "ideogram_v3_pro": {
      "command": "npx",
      "args": [
        "-y",
        "mcp-remote",
        "https://prod.api.market/api/mcp/magicapi/ideogram-v3-pro-text-to-image",
        "--header",
        "x-api-market-key: ${API_MARKET_KEY}"
      ],
      "env": {
        "API_MARKET_KEY": "your_actual_api_key_here"
      }
    },
    "flux_8b": {
      "command": "npx",
      "args": [
        "-y",
        "mcp-remote",
        "https://prod.api.market/api/mcp/magicapi/flux-8b-text-to-image",
        "--header",
        "x-api-market-key: ${API_MARKET_KEY}"
      ],
      "env": {
        "API_MARKET_KEY": "your_actual_api_key_here"
      }
    },
    "domain_checker": {
      "command": "npx",
      "args": [
        "-y",
        "mcp-remote",
        "https://prod.api.market/api/mcp/magicapi/domainchecker",
        "--header",
        "x-api-market-key: ${API_MARKET_KEY}"
      ],
      "env": {
        "API_MARKET_KEY": "your_actual_api_key_here"
      }
    }
  }
}
```

**Setup Instructions**

1. Open Claude Desktop
2. Go to Settings → Developer
3. Click "Edit Config" to open the configuration file
4. Add your MCP server configurations
5. Save the file and restart Claude Desktop
6. Look for the MCP tools icon in conversations

#### Cursor IDE

**Configuration File Location**

Access via Cursor Settings → Features → Model Context Protocol

**Configuration Format**

```json
{
  "mcpServers": {
    "ideogram_v3_pro": {
      "url": "https://prod.api.market/api/mcp/magicapi/ideogram-v3-pro-text-to-image",
      "headers": {
        "x-api-market-key": "your_actual_api_key_here"
      }
    }
  }
}
```

**Setup Instructions**

1. Open Cursor IDE
2. Navigate to Settings → Features → Model Context Protocol
3. Click "Add Server"
4. Paste the configuration
5. Restart Cursor
6. The API tools will be available in AI conversations

#### Python Client

**Installation**

```bash
pip install requests
```

**Implementation**

```python
import requests
import json

class APIMarketMCPClient:
    def __init__(self, api_key: str, workspace: str, api_slug: str):
        self.endpoint = f"https://prod.api.market/api/mcp/{workspace}/{api_slug}"
        self.headers = {
            "Content-Type": "application/json",
            "x-api-market-key": api_key
        }
        self.request_id = 0
    
    def _call(self, method: str, params: dict = None) -> dict:
        """Make a JSON-RPC call to the MCP server"""
        self.request_id += 1
        payload = {
            "jsonrpc": "2.0",
            "id": self.request_id,
            "method": method
        }
        if params:
            payload["params"] = params
            
        response = requests.post(
            self.endpoint, 
            json=payload, 
            headers=self.headers
        )
        return response.json()
    
    def initialize(self) -> dict:
        """Initialize the MCP connection"""
        return self._call("initialize", {
            "protocolVersion": "2024-11-05",
            "capabilities": {"tools": {}},
            "clientInfo": {"name": "Python Client", "version": "1.0.0"}
        })
    
    def list_tools(self) -> dict:
        """List all available tools"""
        return self._call("tools/list")
    
    def call_tool(self, name: str, arguments: dict) -> dict:
        """Call a specific tool"""
        return self._call("tools/call", {
            "name": name,
            "arguments": arguments
        })
    
    def list_resources(self) -> dict:
        """List available resources"""
        return self._call("resources/list")
    
    def get_resource(self, uri: str) -> dict:
        """Get a specific resource"""
        return self._call("resources/read", {"uri": uri})

# Example usage
if __name__ == "__main__":
    # Initialize client for Ideogram v3 Pro
    client = APIMarketMCPClient(
        api_key="your_api_key_here",
        workspace="magicapi",
        api_slug="ideogram-v3-pro-text-to-image"
    )
    
    # Initialize connection
    init_result = client.initialize()
    print("Initialized:", init_result)
    
    # Get available tools
    tools = client.list_tools()
    if "result" in tools and "tools" in tools["result"]:
        print("\nAvailable tools:")
        for tool in tools["result"]["tools"]:
            print(f"  - {tool['name']}: {tool.get('description', 'No description')}")
    
    # Example: Generate an image
    result = client.call_tool("createideogram_v3_qualityprediction", {
        "body": {
            "input": {
                "prompt": "A beautiful sunset over mountains",
                "aspect_ratio": "16:9"
            }
        }
    })
    print("Tool result:", result)
```

#### cURL Testing

**Initialize Connection**

```bash
curl -X POST "https://prod.api.market/api/mcp/magicapi/ideogram-v3-pro-text-to-image" \
  -H "Content-Type: application/json" \
  -H "x-api-market-key: YOUR_API_KEY" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "initialize",
    "params": {
      "protocolVersion": "2024-11-05",
      "capabilities": {"tools": {}},
      "clientInfo": {"name": "curl", "version": "1.0.0"}
    }
  }'
```

**List Available Tools**

```bash
curl -X POST "https://prod.api.market/api/mcp/magicapi/ideogram-v3-pro-text-to-image" \
  -H "Content-Type: application/json" \
  -H "x-api-market-key: YOUR_API_KEY" \
  -d '{
    "jsonrpc": "2.0",
    "id": 2,
    "method": "tools/list",
    "params": {}
  }'
```

**Call a Tool**

```bash
curl -X POST "https://prod.api.market/api/mcp/magicapi/ideogram-v3-pro-text-to-image" \
  -H "Content-Type: application/json" \
  -H "x-api-market-key: YOUR_API_KEY" \
  -d '{
    "jsonrpc": "2.0",
    "id": 3,
    "method": "tools/call",
    "params": {
      "name": "createideogram_v3_qualityprediction",
      "arguments": {
        "body": {
          "input": {
            "prompt": "A professional logo design",
            "aspect_ratio": "1:1"
          }
        }
      }
    }
  }'
```

***

### API Examples

#### Image Generation APIs

**Ideogram v3 Pro - Text to Image**

**MCP Endpoint**: `https://prod.api.market/api/mcp/magicapi/ideogram-v3-pro-text-to-image`

**Available Tools**:

* `createideogram_v3_qualityprediction`: Generate images with advanced text rendering
* `getideogram_v3_qualityprediction`: Get prediction status and results

**Example Usage in Claude**:

```
Generate a professional logo for "TechFlow Solutions" with modern typography, 
blue and silver colors, suitable for both light and dark backgrounds.
```

**Flux.1 8B - Fast Text to Image**

**MCP Endpoint**: `https://prod.api.market/api/mcp/magicapi/flux-8b-text-to-image`

**Available Tools**:

* `createflux_8b_prediction`: Fast image generation
* `getflux_8b_prediction`: Get prediction results

**Example Usage in Claude**:

```
Create a product mockup of a smartphone with a sleek design, 
gradient background, professional lighting, 4K quality.
```

#### Utility APIs

**Domain Checker**

**MCP Endpoint**: `https://prod.api.market/api/mcp/magicapi/domainchecker`

**Available Tools**:

* `checkdomainavailability`: Check if domains are available for registration

**Example Usage in Claude**:

```
Check if these domains are available: techflow.com, techflow.io, techflow.ai
```

**Geocoding APIs**

**MCP Endpoint**: `https://prod.api.market/api/mcp/trueway/geocoding`

**Available Tools**:

* `forward_geocoding`: Convert addresses to coordinates
* `reverse_geocoding`: Convert coordinates to addresses

**Example Usage in Claude**:

```
Find the coordinates for "1600 Amphitheatre Parkway, Mountain View, CA"
```

#### Video Generation APIs

**SeedDance Pro - Image to Video**

**MCP Endpoint**: `https://prod.api.market/api/mcp/byteplus/seedance-image-to-video-pro`

**Available Tools**:

* `createvideo_generation`: Convert images to videos with motion

**Example Usage in Claude**:

```
Take this product image and create a 5-second video with smooth 360-degree rotation, 
professional lighting, and subtle zoom effect.
```

#### Audio APIs

**Kokoro v1.0 - Text to Speech**

**MCP Endpoint**: `https://prod.api.market/api/mcp/magicapi/kokoro-v1-text-to-speech`

**Available Tools**:

* `createtts_generation`: Generate natural-sounding speech

**Example Usage in Claude**:

```
Generate a professional voiceover for this script: "Welcome to TechFlow Solutions, 
where innovation meets efficiency."
```

***

### Advanced Usage

#### Multi-API Workflows

With multiple MCP servers configured, you can create complex workflows:

```
1. Check domain availability for "myapp.com"
2. If available, generate a logo for "MyApp" 
3. Create a product mockup showing the logo
4. Generate a promotional video from the mockup
5. Add a voiceover explaining the app's benefits
```

#### Batch Processing

```python
# Example: Generate multiple logo variations
logos = [
    {"style": "modern", "colors": "blue and white"},
    {"style": "classic", "colors": "gold and black"},
    {"style": "playful", "colors": "rainbow gradients"}
]

for logo_config in logos:
    result = client.call_tool("createideogram_v3_qualityprediction", {
        "body": {
            "input": {
                "prompt": f"Create a {logo_config['style']} logo using {logo_config['colors']} colors",
                "aspect_ratio": "1:1"
            }
        }
    })
    print(f"Generated {logo_config['style']} logo:", result)
```

#### Error Handling

```python
def safe_api_call(client, tool_name, arguments):
    try:
        result = client.call_tool(tool_name, arguments)
        if "error" in result:
            print(f"API Error: {result['error']}")
            return None
        return result["result"]
    except Exception as e:
        print(f"Network Error: {e}")
        return None
```

***

### Best Practices

#### 1. Authentication Security

* **Never hardcode API keys** in shared code
* **Use environment variables** for API keys
* **Rotate keys regularly** for security
* **Monitor usage** through API.Market dashboard

#### 2. Prompt Engineering

**For Image Generation**

```
Structure: [Subject] + [Style] + [Composition] + [Lighting] + [Technical specs]

Good: "Modern smartphone, minimalist product photography, centered composition, 
soft studio lighting, 4K resolution, white background"

Poor: "Phone picture"
```

**For API Tools**

```
Be specific about parameters:

Good: "Generate a 1920x1080 image with aspect ratio 16:9"
Poor: "Make it big"
```

#### 3. Resource Management

* **Cache results** when possible
* **Batch similar requests** together
* **Use appropriate quality settings** for different use cases
* **Monitor API quotas** and usage

#### 4. Error Handling

* **Implement retry logic** for transient failures
* **Validate inputs** before API calls
* **Handle rate limiting** gracefully
* **Log errors** for debugging

#### 5. Performance Optimization

**Choose the Right API**

* **Development**: Use faster, cheaper APIs (Flux.1 8B)
* **Production**: Use premium APIs (Ideogram v3 Pro)
* **Bulk operations**: Use volume-optimized APIs

**Optimize Requests**

```python
# Good: Specific, efficient prompt
prompt = "Professional headshot, corporate style, neutral background, high resolution"

# Poor: Vague, might require multiple attempts
prompt = "Make it look good"
```

***

### Troubleshooting

#### Common Issues

**1. MCP Server Not Connecting**

**Symptoms**:

* Claude/Cursor shows "Server not available"
* No MCP tools appearing in interface

**Solutions**:

```bash
# Check Node.js version
node --version  # Should be 18+

# Test MCP endpoint directly
curl -X POST "https://prod.api.market/api/mcp/magicapi/domainchecker" \
  -H "Content-Type: application/json" \
  -H "x-api-market-key: YOUR_API_KEY" \
  -d '{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}'

# Verify API key is valid
# Check API.Market dashboard for key status
```

**2. Authentication Errors**

**Symptoms**:

* "Invalid API key" errors
* "Unauthorized" responses

**Solutions**:

1. Verify API key in API.Market dashboard
2. Check key hasn't expired
3. Ensure sufficient credits/subscription
4. Confirm key format (no extra spaces/characters)

**3. Slow Response Times**

**Symptoms**:

* Long wait times for responses
* Timeouts in MCP clients

**Solutions**:

1. Use faster APIs for testing (Flux.1 8B vs Ideogram v3 Pro)
2. Reduce image resolution for drafts
3. Simplify prompts
4. Check API.Market status page

**4. Tool Not Found Errors**

**Symptoms**:

* "Tool not available" messages
* Missing expected functionality

**Solutions**:

1. Run `tools/list` to see available tools
2. Check tool name spelling
3. Verify API subscription status
4. Restart MCP client

#### Debugging Steps

**1. Test MCP Connection**

```bash
# Test basic connectivity
curl -X POST "https://prod.api.market/api/mcp/magicapi/domainchecker" \
  -H "Content-Type: application/json" \
  -H "x-api-market-key: YOUR_API_KEY" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "initialize",
    "params": {
      "protocolVersion": "2024-11-05",
      "capabilities": {"tools": {}},
      "clientInfo": {"name": "debug", "version": "1.0.0"}
    }
  }'
```

**2. List Available Tools**

```bash
curl -X POST "https://prod.api.market/api/mcp/magicapi/domainchecker" \
  -H "Content-Type: application/json" \
  -H "x-api-market-key: YOUR_API_KEY" \
  -d '{
    "jsonrpc": "2.0",
    "id": 2,
    "method": "tools/list",
    "params": {}
  }'
```

**3. Validate Configuration**

```python
import json

# Validate JSON configuration
config = '''
{
  "mcpServers": {
    "domain_checker": {
      "command": "npx",
      "args": ["-y", "mcp-remote", "https://prod.api.market/api/mcp/magicapi/domainchecker", "--header", "x-api-market-key: YOUR_KEY"],
      "env": {"API_MARKET_KEY": "YOUR_KEY"}
    }
  }
}
'''

try:
    parsed = json.loads(config)
    print("✅ Configuration is valid JSON")
except json.JSONDecodeError as e:
    print(f"❌ Invalid JSON: {e}")
```

***

### Cost Optimization

You must have an active subscription for the given API that you want to use in MCP. Most APIs have a generoud free plan for you to try.

#### Optimization Strategies

**1. API Selection**

```python
# Cost-effective development workflow
development_apis = {
    "quick_testing": "flux-8b-text-to-image",      # Fast & cheap
    "final_production": "ideogram-v3-pro",          # Premium quality
    "batch_processing": "seedream-text-to-image"    # Volume discounts
}
```

**2. Prompt Optimization**

```python
# Efficient: Single prompt, multiple variations
prompt = "Create 3 logo variations for TechFlow: modern, classic, and playful styles"

# Inefficient: Multiple separate calls
# "Create a modern logo for TechFlow"
# "Create a classic logo for TechFlow"  
# "Create a playful logo for TechFlow"
```

**3. Caching Strategy**

```python
import hashlib
import json

def cache_key(tool_name, arguments):
    """Generate cache key for API calls"""
    content = f"{tool_name}:{json.dumps(arguments, sort_keys=True)}"
    return hashlib.md5(content.encode()).hexdigest()

# Cache expensive operations
cache = {}
key = cache_key("createideogram_v3_qualityprediction", arguments)
if key in cache:
    return cache[key]
    
result = client.call_tool("createideogram_v3_qualityprediction", arguments)
cache[key] = result
return result
```

**4. Quality Tiers**

```python
# Development: Use lower quality for iterations
dev_settings = {
    "resolution": "512x512",
    "quality": "standard",
    "iterations": 1
}

# Production: Use premium settings for final output
prod_settings = {
    "resolution": "2048x2048", 
    "quality": "premium",
    "iterations": 4
}
```

***

### FAQ

#### General Questions

**Q: Do I need to install anything to use MCP servers?** \
A: For most clients (Claude Desktop, Cursor), you only need Node.js 18+. The MCP clients handle the rest automatically.

**Q: Can I use multiple APIs simultaneously?** \
A: Yes! You can configure multiple MCP servers and use them together in complex workflows.

**Q: Are there rate limits?** \
A: Rate limits depend on your API.Market subscription tier. Check your dashboard for current limits.

**Q: How do I know which tools are available for each API?** \
A: Use the `tools/list` method or ask your AI client "What tools do you have access to?"

#### Technical Questions

**Q: Can I use MCP servers in my own applications?** \
A: Yes! You can integrate MCP servers into any application that supports the protocol.

**Q: What happens if an API call fails?** \
A: The MCP server returns a JSON-RPC error response with details about the failure.

**Q: Can I customize the tool names?** \
A: Tool names are automatically generated from API endpoints. You can't customize them, but you can create wrapper functions.

**Q: How do I handle long-running operations?** \
A: Some APIs support async operations. Check the API documentation for polling endpoints.

#### Billing Questions

**Q: How am I charged for MCP usage?** \
A: You're charged the same rates as direct API usage. MCP doesn't add any additional fees.

**Q: Can I set spending limits?** \
A: Yes, you can set spending limits in your API.Market dashboard.

**Q: Are there volume discounts?** \
A: Volume discounts are available for high-usage scenarios. Contact support for details.

***

### Support and Resources

#### Documentation

* [API.Market Main Documentation](https://docs.api.market)
* [MCP Protocol Specification](https://modelcontextprotocol.io)
* [Individual API Documentation](https://api.market/search)

#### Support

* Email: <support@api.market>
* Live Chat: Available on api.market
* Status Page: [https://status.api.market](https://status.api.market/status/dash)

***
