gpt4free MCP Server

A Model Context Protocol (MCP) server implementation for gpt4free that provides AI assistants with access to web search, scraping, and image generation capabilities.

Overview

The gpt4free MCP server exposes three main tools:

  1. Web Search - Search the web using DuckDuckGo
  2. Web Scraping - Extract and clean text content from web pages
  3. Image Generation - Generate images from text prompts using various AI providers

Installation

The MCP server is included with gpt4free. No additional installation is required beyond the base gpt4free package.

pip install -e .

Usage

Running the MCP Server

Stdio Mode (Default)

Start the MCP server using:

python -m g4f.mcp

Or using the g4f command:

g4f mcp

The server communicates over stdin/stdout using JSON-RPC 2.0 protocol.

HTTP Mode

Start the MCP server with HTTP transport:

g4f mcp --http --port 8765

This starts an HTTP server with the following endpoints:

HTTP mode is useful for:

Options:

Configuration for AI Assistants

For Claude Desktop (Stdio) - claude_desktop_config.json:

{
  "mcpServers": {
    "gpt4free": {
      "command": "python",
      "args": ["-m", "g4f.mcp"]
    }
  }
}

For HTTP-based clients:

Make POST requests to http://localhost:8765/mcp with JSON-RPC payloads.

Example with curl:

curl -X POST http://localhost:8765/mcp \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'

For VS Code with Cline:

{
  "mcpServers": {
    "gpt4free": {
      "command": "python",
      "args": ["-m", "g4f.mcp"],
      "disabled": false
    }
  }
}

Available Tools

web_search

Search the web for information.

Parameters:

Example:

{
  "name": "web_search",
  "arguments": {
    "query": "latest AI developments 2024",
    "max_results": 5
  }
}

web_scrape

Scrape and extract text content from a web page.

Parameters:

Example:

{
  "name": "web_scrape",
  "arguments": {
    "url": "https://example.com/article",
    "max_words": 1000
  }
}

image_generation

Generate images from text prompts.

Parameters:

Example:

{
  "name": "image_generation",
  "arguments": {
    "prompt": "A serene mountain landscape at sunset",
    "width": 1024,
    "height": 1024
  }
}

Protocol Details

The MCP server implements the Model Context Protocol using JSON-RPC 2.0 over stdio transport.

Supported Methods

Example Request/Response

Request:

{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "web_search",
    "arguments": {
      "query": "Python programming tutorials",
      "max_results": 3
    }
  }
}

Response:

{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "{\"query\": \"Python programming tutorials\", \"results\": [...], \"count\": 3}"
      }
    ]
  }
}

Requirements

The MCP server requires the following dependencies (included in gpt4free):

These are automatically installed with:

pip install -r requirements.txt

Error Handling

The server returns standard JSON-RPC error responses:

Errors specific to tools are returned in the result object with an error field.

Development

Project Structure

g4f/mcp/
├── __init__.py      # Package initialization
├── __main__.py      # CLI entry point
├── server.py        # MCP server implementation
├── tools.py         # Tool implementations
└── README.md        # This file

Adding New Tools

To add a new tool:

  1. Create a new class inheriting from MCPTool in tools.py
  2. Implement the required properties and methods
  3. Register the tool in MCPServer.__init__() in server.py

Example:

class MyNewTool(MCPTool):
    @property
    def description(self) -> str:
        return "Description of what the tool does"
    
    @property
    def input_schema(self) -> Dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "param1": {
                    "type": "string",
                    "description": "Parameter description"
                }
            },
            "required": ["param1"]
        }
    
    async def execute(self, arguments: Dict[str, Any]) -> Any:
        # Implementation
        pass

Troubleshooting

Server Won't Start

Make sure all dependencies are installed:

pip install -r requirements.txt

Tools Return Errors

Check that:

Debug Mode

The server writes diagnostic information to stderr. To see debug output:

python -m g4f.mcp 2> debug.log

License

This MCP server is part of the gpt4free project and is licensed under the GNU General Public License v3.0.

Contributing

Contributions are welcome! Please see the main gpt4free repository for contribution guidelines.

Related Links