返回提交历史
Deleted
docs/mcp-usage-guide.md
+0
-440
Modified
g4f/api/__init__.py
+1
-1
Deleted
g4f/mcp/README.md
+0
-316
Modified
g4f/mcp/tools.py
+10
-2
XFEstudio/gpt4free
Remove MCP usage guide and README files; update logging in API to use print for most wanted IPs; enhance WebSearchTool to support region parameter for search queries.
5276e2d6
代码差异
4 个文件
+11
-759
@@ -1,440 +0,0 @@
1
# gpt4free MCP Server - Complete Usage Guide
2
3
## Table of Contents
4
- [Introduction](#introduction)
5
- [Quick Start](#quick-start)
6
- [Configuration](#configuration)
7
- [Available Tools](#available-tools)
8
- [Integration Examples](#integration-examples)
9
- [Troubleshooting](#troubleshooting)
10
11
## Introduction
12
13
The gpt4free MCP (Model Context Protocol) server enables AI assistants like Claude to access powerful capabilities:
14
- **Web Search**: Real-time web search using DuckDuckGo
15
- **Web Scraping**: Extract and clean text content from any web page
16
- **Image Generation**: Create images from text descriptions using various AI models
17
18
## Quick Start
19
20
### 1. Installation
21
22
Make sure gpt4free is installed with all dependencies:
23
24
```bash
25
# Install with all features
26
pip install -U g4f[all]
27
28
# Or install from source
29
git clone https://github.com/xtekky/gpt4free.git
30
cd gpt4free
31
pip install -e .
32
```
33
34
### 2. Start the MCP Server
35
36
**Stdio Mode (Default):**
37
38
```bash
39
# Using g4f command
40
g4f mcp
41
42
# Or using Python module
43
python -m g4f.mcp
44
45
# With debug logging
46
g4f mcp --debug
47
```
48
49
The server will:
50
- Listen on stdin for JSON-RPC requests
51
- Write responses to stdout
52
- Write debug/error messages to stderr
53
54
**HTTP Mode:**
55
56
```bash
57
# Start HTTP server on default port 8765
58
g4f mcp --http
59
60
# Custom port
61
g4f mcp --http --port 3000
62
63
# Custom host and port
64
g4f mcp --http --host 127.0.0.1 --port 8765
65
```
66
67
The HTTP server provides:
68
- `POST http://localhost:8765/mcp` - JSON-RPC endpoint
69
- `GET http://localhost:8765/health` - Health check endpoint
70
71
HTTP mode is useful for:
72
- Web-based integrations
73
- Testing with HTTP clients
74
- Remote access
75
- Debugging with tools like curl or Postman
76
77
### 3. Test the Server
78
79
**Stdio Mode:**
80
81
```bash
82
# Send a test request
83
echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}' | python -m g4f.mcp
84
```
85
86
Expected output:
87
```json
88
{"jsonrpc": "2.0", "id": 1, "result": {"protocolVersion": "2024-11-05", "serverInfo": {...}}}
89
```
90
91
**HTTP Mode:**
92
93
```bash
94
# Start server
95
g4f mcp --http --port 8765
96
97
# In another terminal, test with curl
98
curl -X POST http://localhost:8765/mcp \
99
-H "Content-Type: application/json" \
100
-d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}'
101
102
# Health check
103
curl http://localhost:8765/health
104
```
105
106
## Configuration
107
108
### Claude Desktop
109
110
1. Locate your config file:
111
- **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
112
- **Windows**: `%APPDATA%/Claude/claude_desktop_config.json`
113
- **Linux**: `~/.config/Claude/claude_desktop_config.json`
114
115
2. Add the MCP server:
116
117
```json
118
{
119
"mcpServers": {
120
"gpt4free": {
121
"command": "python",
122
"args": ["-m", "g4f.mcp"],
123
"description": "gpt4free MCP server with web search, scraping, and image generation"
124
}
125
}
126
}
127
```
128
129
3. Restart Claude Desktop
130
131
4. Verify in Claude: Ask "What tools do you have access to?" and you should see the gpt4free tools listed.
132
133
### VS Code with Cline Extension
134
135
Add to your Cline MCP settings:
136
137
```json
138
{
139
"mcpServers": {
140
"gpt4free": {
141
"command": "python",
142
"args": ["-m", "g4f.mcp"],
143
"disabled": false
144
}
145
}
146
}
147
```
148
149
### Other MCP Clients
150
151
Any MCP-compatible client can use the server. The command is:
152
```bash
153
python -m g4f.mcp
154
```
155
156
## Available Tools
157
158
### 1. web_search
159
160
Search the web for current information.
161
162
**Parameters:**
163
- `query` (string, required): Search query
164
- `max_results` (integer, optional): Maximum results to return (default: 5)
165
166
**Example Request:**
167
```json
168
{
169
"jsonrpc": "2.0",
170
"id": 1,
171
"method": "tools/call",
172
"params": {
173
"name": "web_search",
174
"arguments": {
175
"query": "latest Python 3.12 features",
176
"max_results": 5
177
}
178
}
179
}
180
```
181
182
**Example Usage in Claude:**
183
> "Search the web for the latest Python 3.12 features"
184
185
### 2. web_scrape
186
187
Extract text content from web pages.
188
189
**Parameters:**
190
- `url` (string, required): URL to scrape
191
- `max_words` (integer, optional): Maximum words to extract (default: 1000)
192
193
**Example Request:**
194
```json
195
{
196
"jsonrpc": "2.0",
197
"id": 2,
198
"method": "tools/call",
199
"params": {
200
"name": "web_scrape",
201
"arguments": {
202
"url": "https://python.org",
203
"max_words": 500
204
}
205
}
206
}
207
```
208
209
**Example Usage in Claude:**
210
> "Scrape the content from https://python.org and summarize it"
211
212
### 3. image_generation
213
214
Generate images from text descriptions.
215
216
**Parameters:**
217
- `prompt` (string, required): Image description
218
- `model` (string, optional): Image model (default: "flux")
219
- `width` (integer, optional): Width in pixels (default: 1024)
220
- `height` (integer, optional): Height in pixels (default: 1024)
221
222
**Example Request:**
223
```json
224
{
225
"jsonrpc": "2.0",
226
"id": 3,
227
"method": "tools/call",
228
"params": {
229
"name": "image_generation",
230
"arguments": {
231
"prompt": "A serene mountain landscape at sunset",
232
"width": 1024,
233
"height": 1024
234
}
235
}
236
}
237
```
238
239
**Example Usage in Claude:**
240
> "Generate an image of a serene mountain landscape at sunset"
241
242
## Integration Examples
243
244
### Python Script
245
246
```python
247
import asyncio
248
import json
249
from g4f.mcp.server import MCPServer, MCPRequest
250
251
async def search_web(query: str):
252
server = MCPServer()
253
request = MCPRequest(
254
jsonrpc="2.0",
255
id=1,
256
method="tools/call",
257
params={
258
"name": "web_search",
259
"arguments": {"query": query}
260
}
261
)
262
response = await server.handle_request(request)
263
return response.result
264
265
# Run it
266
result = asyncio.run(search_web("Python tutorials"))
267
print(result)
268
```
269
270
### Command Line Testing
271
272
```bash
273
# Test initialize
274
echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}' | g4f mcp
275
276
# Test list tools
277
echo '{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}' | g4f mcp
278
279
# Test web search
280
echo '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"web_search","arguments":{"query":"test"}}}' | g4f mcp
281
```
282
283
### Using with Shell Scripts
284
285
```bash
286
#!/bin/bash
287
# search.sh - Simple web search wrapper
288
289
query="$1"
290
request=$(cat <<EOF
291
{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"web_search","arguments":{"query":"$query"}}}
292
EOF
293
)
294
295
echo "$request" | python -m g4f.mcp | jq '.result.content[0].text | fromjson'
296
```
297
298
## Troubleshooting
299
300
### Server Won't Start
301
302
**Problem**: Server exits immediately or shows import errors
303
304
**Solution**:
305
```bash
306
# Install all dependencies
307
pip install -r requirements.txt
308
309
# Or install with all extras
310
pip install -U g4f[all]
311
```
312
313
### Tools Return Errors
314
315
**Problem**: Tools return error messages about missing packages
316
317
**Solution**: Install specific dependencies:
318
```bash
319
# For web search
320
pip install ddgs beautifulsoup4
321
322
# For web scraping
323
pip install aiohttp beautifulsoup4
324
325
# For image generation
326
pip install pillow
327
```
328
329
### Network Errors
330
331
**Problem**: Tools fail with connection errors
332
333
**Solution**:
334
- Check internet connectivity
335
- Some providers may be rate-limited
336
- Try different providers for image generation
337
- Check firewall settings
338
339
### Claude Desktop Not Finding Server
340
341
**Problem**: Claude doesn't show gpt4free tools
342
343
**Solution**:
344
1. Verify config file location and syntax
345
2. Check that Python is in PATH
346
3. Try absolute path to Python:
347
```json
348
{
349
"mcpServers": {
350
"gpt4free": {
351
"command": "/usr/bin/python3",
352
"args": ["-m", "g4f.mcp"]
353
}
354
}
355
}
356
```
357
4. Restart Claude Desktop completely
358
5. Check Claude logs for errors
359
360
### Debug Mode
361
362
Enable debug output:
363
```bash
364
# Redirect stderr to see debug messages
365
g4f mcp 2> mcp_debug.log
366
367
# Run with verbose output
368
g4f mcp --debug 2>&1 | tee mcp_output.log
369
```
370
371
### Verify Installation
372
373
Run the test script:
374
```bash
375
python etc/testing/test_mcp_server.py
376
```
377
378
Or the interactive demo:
379
```bash
380
python etc/testing/test_mcp_interactive.py
381
```
382
383
## Protocol Details
384
385
The MCP server implements JSON-RPC 2.0 over stdio transport.
386
387
**Supported Methods:**
388
- `initialize` - Initialize the connection
389
- `tools/list` - List all available tools
390
- `tools/call` - Execute a tool
391
- `ping` - Health check
392
393
**Message Format:**
394
- Requests: One JSON object per line on stdin
395
- Responses: One JSON object per line on stdout
396
- Logs: Messages on stderr
397
398
## Advanced Usage
399
400
### Custom Tool Development
401
402
To add custom tools, see `g4f/mcp/tools.py`:
403
404
```python
405
from g4f.mcp.tools import MCPTool
406
407
class MyCustomTool(MCPTool):
408
@property
409
def description(self) -> str:
410
return "My custom tool description"
411
412
@property
413
def input_schema(self) -> Dict[str, Any]:
414
return {
415
"type": "object",
416
"properties": {
417
"param1": {"type": "string", "description": "..."}
418
},
419
"required": ["param1"]
420
}
421
422
async def execute(self, arguments: Dict[str, Any]) -> Any:
423
# Your implementation
424
pass
425
```
426
427
Register in `g4f/mcp/server.py`:
428
```python
429
self.tools['my_tool'] = MyCustomTool()
430
```
431
432
## Support
433
434
- Documentation: [g4f/mcp/README.md](README.md)
435
- Issues: https://github.com/xtekky/gpt4free/issues
436
- MCP Specification: https://modelcontextprotocol.io/
437
438
## License
439
440
Part of the gpt4free project, licensed under GNU General Public License v3.0.
@@ -456,7 +456,7 @@ class Api:
456
456
else:
457
457
most_wanted[x_forwarded_for] = 1
458
458
sorted_most_wanted = dict(sorted(most_wanted.items(), key=lambda item: item[1], reverse=True))
459
debug.log(f"Most wanted IPs: {sorted_most_wanted}")
459
print(f"Most wanted IPs: {json.dumps(sorted_most_wanted, indent=2)}")
460
460
if is_most_wanted:
461
461
return ErrorResponse.from_message("You are most wanted! Please wait before making another request.", status_code=HTTP_429_TOO_MANY_REQUESTS)
462
462
if provider is not None and provider not in Provider.__map__:
@@ -1,316 +0,0 @@
1
# gpt4free MCP Server
2
3
A Model Context Protocol (MCP) server implementation for gpt4free that provides AI assistants with access to web search, scraping, and image generation capabilities.
4
5
## Overview
6
7
The gpt4free MCP server exposes three main tools:
8
9
1. **Web Search** - Search the web using DuckDuckGo
10
2. **Web Scraping** - Extract and clean text content from web pages
11
3. **Image Generation** - Generate images from text prompts using various AI providers
12
13
## Installation
14
15
The MCP server is included with gpt4free. No additional installation is required beyond the base gpt4free package.
16
17
```bash
18
pip install -e .
19
```
20
21
## Usage
22
23
### Running the MCP Server
24
25
**Stdio Mode (Default)**
26
27
Start the MCP server using:
28
29
```bash
30
python -m g4f.mcp
31
```
32
33
Or using the g4f command:
34
35
```bash
36
g4f mcp
37
```
38
39
The server communicates over stdin/stdout using JSON-RPC 2.0 protocol.
40
41
**HTTP Mode**
42
43
Start the MCP server with HTTP transport:
44
45
```bash
46
g4f mcp --http --port 8765
47
```
48
49
This starts an HTTP server with the following endpoints:
50
- `POST http://localhost:8765/mcp` - MCP JSON-RPC endpoint
51
- `GET http://localhost:8765/health` - Health check endpoint
52
53
HTTP mode is useful for:
54
- Web-based integrations
55
- Testing with curl or HTTP clients
56
- Remote access (configure host with `--host`)
57
58
Options:
59
- `--http`: Enable HTTP transport instead of stdio
60
- `--host HOST`: Host to bind to (default: 0.0.0.0)
61
- `--port PORT`: Port to bind to (default: 8765)
62
63
### Configuration for AI Assistants
64
65
**For Claude Desktop (Stdio)** - `claude_desktop_config.json`:
66
67
```json
68
{
69
"mcpServers": {
70
"gpt4free": {
71
"command": "python",
72
"args": ["-m", "g4f.mcp"]
73
}
74
}
75
}
76
```
77
78
**For HTTP-based clients**:
79
80
Make POST requests to `http://localhost:8765/mcp` with JSON-RPC payloads.
81
82
Example with curl:
83
```bash
84
curl -X POST http://localhost:8765/mcp \
85
-H "Content-Type: application/json" \
86
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'
87
```
88
89
**For VS Code with Cline**:
90
91
```json
92
{
93
"mcpServers": {
94
"gpt4free": {
95
"command": "python",
96
"args": ["-m", "g4f.mcp"],
97
"disabled": false
98
}
99
}
100
}
101
```
102
103
## Available Tools
104
105
### web_search
106
107
Search the web for information.
108
109
**Parameters:**
110
- `query` (string, required): The search query
111
- `max_results` (integer, optional): Maximum number of results (default: 5)
112
113
**Example:**
114
```json
115
{
116
"name": "web_search",
117
"arguments": {
118
"query": "latest AI developments 2024",
119
"max_results": 5
120
}
121
}
122
```
123
124
### web_scrape
125
126
Scrape and extract text content from a web page.
127
128
**Parameters:**
129
- `url` (string, required): The URL to scrape
130
- `max_words` (integer, optional): Maximum words to extract (default: 1000)
131
132
**Example:**
133
```json
134
{
135
"name": "web_scrape",
136
"arguments": {
137
"url": "https://example.com/article",
138
"max_words": 1000
139
}
140
}
141
```
142
143
### image_generation
144
145
Generate images from text prompts.
146
147
**Parameters:**
148
- `prompt` (string, required): Description of the image to generate
149
- `model` (string, optional): Image model to use (default: "flux")
150
- `width` (integer, optional): Image width in pixels (default: 1024)
151
- `height` (integer, optional): Image height in pixels (default: 1024)
152
153
**Example:**
154
```json
155
{
156
"name": "image_generation",
157
"arguments": {
158
"prompt": "A serene mountain landscape at sunset",
159
"width": 1024,
160
"height": 1024
161
}
162
}
163
```
164
165
## Protocol Details
166
167
The MCP server implements the Model Context Protocol using JSON-RPC 2.0 over stdio transport.
168
169
### Supported Methods
170
171
- `initialize` - Initialize connection with the server
172
- `tools/list` - List all available tools
173
- `tools/call` - Execute a tool with given arguments
174
- `ping` - Health check
175
176
### Example Request/Response
177
178
**Request:**
179
```json
180
{
181
"jsonrpc": "2.0",
182
"id": 1,
183
"method": "tools/call",
184
"params": {
185
"name": "web_search",
186
"arguments": {
187
"query": "Python programming tutorials",
188
"max_results": 3
189
}
190
}
191
}
192
```
193
194
**Response:**
195
```json
196
{
197
"jsonrpc": "2.0",
198
"id": 1,
199
"result": {
200
"content": [
201
{
202
"type": "text",
203
"text": "{\"query\": \"Python programming tutorials\", \"results\": [...], \"count\": 3}"
204
}
205
]
206
}
207
}
208
```
209
210
## Requirements
211
212
The MCP server requires the following dependencies (included in gpt4free):
213
214
- `aiohttp` - For async HTTP requests
215
- `beautifulsoup4` - For web scraping
216
- `ddgs` - For web search
217
218
These are automatically installed with:
219
220
```bash
221
pip install -r requirements.txt
222
```
223
224
## Error Handling
225
226
The server returns standard JSON-RPC error responses:
227
228
- `-32601`: Method not found
229
- `-32602`: Invalid parameters
230
- `-32603`: Internal error
231
232
Errors specific to tools are returned in the result object with an `error` field.
233
234
## Development
235
236
### Project Structure
237
238
```
239
g4f/mcp/
240
├── __init__.py # Package initialization
241
├── __main__.py # CLI entry point
242
├── server.py # MCP server implementation
243
├── tools.py # Tool implementations
244
└── README.md # This file
245
```
246
247
### Adding New Tools
248
249
To add a new tool:
250
251
1. Create a new class inheriting from `MCPTool` in `tools.py`
252
2. Implement the required properties and methods
253
3. Register the tool in `MCPServer.__init__()` in `server.py`
254
255
Example:
256
257
```python
258
class MyNewTool(MCPTool):
259
@property
260
def description(self) -> str:
261
return "Description of what the tool does"
262
263
@property
264
def input_schema(self) -> Dict[str, Any]:
265
return {
266
"type": "object",
267
"properties": {
268
"param1": {
269
"type": "string",
270
"description": "Parameter description"
271
}
272
},
273
"required": ["param1"]
274
}
275
276
async def execute(self, arguments: Dict[str, Any]) -> Any:
277
# Implementation
278
pass
279
```
280
281
## Troubleshooting
282
283
### Server Won't Start
284
285
Make sure all dependencies are installed:
286
```bash
287
pip install -r requirements.txt
288
```
289
290
### Tools Return Errors
291
292
Check that:
293
- Network connectivity is available for web search and scraping
294
- URLs are valid and accessible
295
- Image generation providers are not rate-limited
296
297
### Debug Mode
298
299
The server writes diagnostic information to stderr. To see debug output:
300
```bash
301
python -m g4f.mcp 2> debug.log
302
```
303
304
## License
305
306
This MCP server is part of the gpt4free project and is licensed under the GNU General Public License v3.0.
307
308
## Contributing
309
310
Contributions are welcome! Please see the main gpt4free repository for contribution guidelines.
311
312
## Related Links
313
314
- [gpt4free Repository](https://github.com/xtekky/gpt4free)
315
- [Model Context Protocol Specification](https://modelcontextprotocol.io/)
316
- [MCP Documentation](https://modelcontextprotocol.io/docs)
@@ -61,6 +61,10 @@ class WebSearchTool(MCPTool):
61
61
"type": "integer",
62
62
"description": "Maximum number of results to return (default: 5)",
63
63
"default": 5
64
},
65
"region": {
66
"type": "string",
67
"description": "Search region (default: en-us)"
64
68
}
65
69
},
66
70
"required": ["query"]
@@ -76,6 +80,7 @@ class WebSearchTool(MCPTool):
76
80
77
81
query = arguments.get("query", "")
78
82
max_results = arguments.get("max_results", 5)
83
region = arguments.get("region", "en-us")
79
84
80
85
if not query:
81
86
return {
@@ -88,7 +93,9 @@ class WebSearchTool(MCPTool):
88
93
search_results = await anext(CachedSearch.create_async_generator(
89
94
"",
90
95
[],
91
prompt=query
96
prompt=query,
97
max_results=max_results,
98
region=region
92
99
))
93
100
94
101
return {
@@ -232,7 +239,8 @@ class ImageGenerationTool(MCPTool):
232
239
model=model,
233
240
prompt=prompt,
234
241
width=width,
235
height=height
242
height=height,
243
response_format="url"
236
244
)
237
245
238
246
# Get the image data with proper validation