What is the Model Context Protocol (MCP) Server Implementation in gpt4free?
The Model Context Protocol (MCP) server in gpt4free is a lightweight JSON-RPC 2.0 service that exposes web search, web scraping, image generation, markdown conversion, and text-to-audio capabilities to external AI agents via STDIO or HTTP transports.
The Model Context Protocol (MCP) is an open standard that enables AI assistants to securely interact with external data sources and tools. In the xtekky/gpt4free repository, the MCP server implementation transforms the library's provider ecosystem into a standardized JSON-RPC interface, allowing Claude Desktop, Cursor, and other MCP-compatible clients to leverage gpt4free's capabilities through a unified API.
Core Architecture Components
The MCP server implementation resides in the g4f/mcp/ directory and follows a modular, async architecture built on JSON-RPC 2.0 standards.
MCPServer Central Dispatcher
At the heart of the implementation is the MCPServer class defined in g4f/mcp/server.py (lines 52-59). This central dispatcher maintains a registry of tool instances and routes incoming JSON-RPC requests to the appropriate handlers. It implements the four core MCP methods:
initialize– Returns server metadata and protocol versiontools/list– Enumerates available tools with their schemastools/call– Executes a specific tool with provided argumentsping– Health check for connection viability
Request and Response Data Models
The server uses simple dataclass containers to model JSON-RPC payloads. The MCPRequest and MCPResponse classes in g4f/mcp/server.py (lines 33-50) provide structured access to the jsonrpc, id, method, params, result, and error fields required by the protocol.
Tool Implementations
Each capability is wrapped as an MCPTool instance. The abstract base class in g4f/mcp/tools.py (lines 18-35) defines the interface:
description– Human-readable tool purposeinput_schema– JSON Schema defining valid parametersexecute()– Async method that performs the actual operation
The server ships with five concrete implementations wrapping existing gpt4free providers:
web_search– Executes web searches via gpt4free search providersweb_scrape– Extracts and cleans content from URLsimage_generation– Generates images using gpt4free image providersmark_it_down– Converts URLs to markdown using the MarkItDown utilitytext_to_audio– Generates audio URLs via Pollinations TTS
Transport Layers
The server supports two distinct transport mechanisms selectable via CLI flags:
STDIO Transport (default) – Implemented in g4f/mcp/server.py (lines 62-100), this transport reads newline-delimited JSON-RPC messages from stdin and writes responses to stdout. This mode is ideal for local AI assistant integrations like Claude Desktop.
HTTP Transport – Activated with the --http flag, this transport creates an aiohttp server (lines 210-236) exposing:
POST /mcp– Primary JSON-RPC endpointGET /health– Server health checkGET /media/{filename}– File serving endpoint for generated content
CLI Integration and Entry Points
The server integrates with the g4f CLI through argument parsing in g4f/cli/__init__.py (lines 253-264). Users can launch the server via:
python -m g4f.mcp(usingg4f/mcp/__main__.py)- The console script
g4f-mcp(installed viasetup.pyentry point)
Available flags include --http, --host, --port, and --origin for configuring the HTTP transport.
How the MCP Server Processes Requests
The request-response flow follows strict JSON-RPC 2.0 semantics with standardized error handling.
STDIO Request Flow
-
The client writes a JSON-RPC line to the server's
stdin, for example:{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}} -
The
run()method reads the line and parses it into anMCPRequestinstance. -
handle_request()matches themethodfield against registered handlers. Forinitialize, it returns a response containing:protocolVersion:"2024-11-05"serverInfo:{"name": "gpt4free-mcp-server", "version": "1.0.0", ...}capabilities:{"tools": {}}
-
The response is serialized to JSON and written to
stdout.
Error Handling Standards
All RPC methods wrap execution in exception handlers to ensure JSON-RPC compliance:
-32603– Internal error (uncaught exceptions during tool execution)-32601– Method not found (invalid tool or method name)
These error codes are defined in the exception handling block at g4f/mcp/server.py (lines 142-150).
Starting and Using the MCP Server
STDIO Transport (Default Mode)
Launch the server for local agent integration:
python -m g4f.mcp
# Or using the installed console script:
g4f-mcp
The server outputs a debug line to stderr:
Starting gpt4free-mcp-server v1.0.0
Test the connection by piping a JSON-RPC request:
echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}' | python -m g4f.mcp
Expected response:
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"protocolVersion": "2024-11-05",
"serverInfo": {
"name": "gpt4free-mcp-server",
"version": "1.0.0",
"description": "MCP server providing web search, scraping, and image generation capabilities"
},
"capabilities": {
"tools": {}
}
}
}
List available tools:
echo '{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}' | python -m g4f.mcp
HTTP Transport
Start the HTTP server on a specific host and port:
python -m g4f.mcp --http --host 127.0.0.1 --port 8765
Execute a web search via the /mcp endpoint:
curl -X POST http://127.0.0.1:8765/mcp \
-H "Content-Type: application/json" \
-d '{
"jsonrpc":"2.0",
"id":3,
"method":"tools/call",
"params":{
"name":"web_search",
"arguments":{"query":"latest python news","max_results":3}
}
}'
The response contains tool results in the standard MCP content format:
{
"jsonrpc":"2.0",
"id":3,
"result":{
"content":[
{"type":"text","text":"{\"query\": \"latest python news\", ...}"}
]
}
}
Direct Python API Integration
For programmatic control, import the server classes directly:
import asyncio
from g4f.mcp.server import MCPServer, MCPRequest
async def search_demo():
server = MCPServer()
request = MCPRequest(
method="tools/call",
params={
"name": "web_search",
"arguments": {"query": "gpt4free repository", "max_results": 2}
}
)
response = await server.handle_request(request)
print(response.result)
asyncio.run(search_demo())
Extending the Server with Custom Tools
The modular architecture allows straightforward extension of server capabilities.
To add a new tool:
- Create a subclass of
MCPTooling4f/mcp/tools.py - Implement the required attributes:
description: Tool description stringinput_schema: JSON Schema dict for parameter validationexecute(): Async method accepting**kwargsand returning results
- Register the instance in
MCPServer.__init__ing4f/mcp/server.py
To implement a custom transport (such as WebSocket), create an async method that reads raw bytes, constructs an MCPRequest, invokes handle_request(), and serializes the MCPResponse back to the client.
Summary
- The gpt4free MCP server exposes the library's capabilities through a standards-compliant JSON-RPC 2.0 interface defined in
g4f/mcp/server.py - It supports dual transport modes: STDIO for local agent integration and HTTP for networked deployments
- Five built-in tools (
web_search,web_scrape,image_generation,mark_it_down,text_to_audio) wrap existing gpt4free providers - The entry points
python -m g4f.mcpandg4f-mcpprovide one-line launchability with configurable flags - Error handling follows JSON-RPC conventions with specific codes for internal errors (-32603) and invalid methods (-32601)
- The architecture is extensible via the
MCPToolabstract base class ing4f/mcp/tools.py
Frequently Asked Questions
What transport protocols does the gpt4free MCP server support?
The server supports STDIO (standard input/output) and HTTP transports. STDIO is the default mode suitable for local AI assistant integration, while HTTP mode (activated with --http) runs an aiohttp server with endpoints for JSON-RPC requests, health checks, and media serving.
How do I add a custom tool to the MCP server?
Subclass MCPTool in g4f/mcp/tools.py and implement the description, input_schema, and execute() interface. Then register your tool instance in the MCPServer class initialization in g4f/mcp/server.py. The server will automatically include your tool in the tools/list response and route tools/call requests to it.
What is the difference between the STDIO and HTTP transports?
STDIO transport reads JSON-RPC messages line-by-line from stdin and writes responses to stdout, making it ideal for local process-to-process communication with agents like Claude Desktop. HTTP transport creates a web server accessible via POST /mcp requests, enabling remote access, CORS support for web clients, and additional endpoints for health monitoring and file serving.
Which error codes does the MCP server return for invalid requests?
The implementation returns -32601 for unknown methods or invalid tool names (method not found), and -32603 for internal server errors that occur during tool execution. These codes follow the JSON-RPC 2.0 specification and are generated in the exception handling logic at lines 142-150 of g4f/mcp/server.py.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →