返回提交历史
Added
docs/mcp-usage-guide.md
+398
-0
Added
etc/examples/mcp_tools_demo.py
+201
-0
XFEstudio/gpt4free
Add comprehensive MCP documentation and examples
Co-authored-by: hlohaus <983577+hlohaus@users.noreply.github.com>
1e895fbb
代码差异
2 个文件
+599
-0
@@ -0,0 +1,398 @@
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
```bash
37
# Using g4f command
38
g4f mcp
39
40
# Or using Python module
41
python -m g4f.mcp
42
43
# With debug logging
44
g4f mcp --debug
45
```
46
47
The server will:
48
- Listen on stdin for JSON-RPC requests
49
- Write responses to stdout
50
- Write debug/error messages to stderr
51
52
### 3. Test the Server
53
54
```bash
55
# Send a test request
56
echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}' | python -m g4f.mcp
57
```
58
59
Expected output:
60
```json
61
{"jsonrpc": "2.0", "id": 1, "result": {"protocolVersion": "2024-11-05", "serverInfo": {...}}}
62
```
63
64
## Configuration
65
66
### Claude Desktop
67
68
1. Locate your config file:
69
- **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
70
- **Windows**: `%APPDATA%/Claude/claude_desktop_config.json`
71
- **Linux**: `~/.config/Claude/claude_desktop_config.json`
72
73
2. Add the MCP server:
74
75
```json
76
{
77
"mcpServers": {
78
"gpt4free": {
79
"command": "python",
80
"args": ["-m", "g4f.mcp"],
81
"description": "gpt4free MCP server with web search, scraping, and image generation"
82
}
83
}
84
}
85
```
86
87
3. Restart Claude Desktop
88
89
4. Verify in Claude: Ask "What tools do you have access to?" and you should see the gpt4free tools listed.
90
91
### VS Code with Cline Extension
92
93
Add to your Cline MCP settings:
94
95
```json
96
{
97
"mcpServers": {
98
"gpt4free": {
99
"command": "python",
100
"args": ["-m", "g4f.mcp"],
101
"disabled": false
102
}
103
}
104
}
105
```
106
107
### Other MCP Clients
108
109
Any MCP-compatible client can use the server. The command is:
110
```bash
111
python -m g4f.mcp
112
```
113
114
## Available Tools
115
116
### 1. web_search
117
118
Search the web for current information.
119
120
**Parameters:**
121
- `query` (string, required): Search query
122
- `max_results` (integer, optional): Maximum results to return (default: 5)
123
124
**Example Request:**
125
```json
126
{
127
"jsonrpc": "2.0",
128
"id": 1,
129
"method": "tools/call",
130
"params": {
131
"name": "web_search",
132
"arguments": {
133
"query": "latest Python 3.12 features",
134
"max_results": 5
135
}
136
}
137
}
138
```
139
140
**Example Usage in Claude:**
141
> "Search the web for the latest Python 3.12 features"
142
143
### 2. web_scrape
144
145
Extract text content from web pages.
146
147
**Parameters:**
148
- `url` (string, required): URL to scrape
149
- `max_words` (integer, optional): Maximum words to extract (default: 1000)
150
151
**Example Request:**
152
```json
153
{
154
"jsonrpc": "2.0",
155
"id": 2,
156
"method": "tools/call",
157
"params": {
158
"name": "web_scrape",
159
"arguments": {
160
"url": "https://python.org",
161
"max_words": 500
162
}
163
}
164
}
165
```
166
167
**Example Usage in Claude:**
168
> "Scrape the content from https://python.org and summarize it"
169
170
### 3. image_generation
171
172
Generate images from text descriptions.
173
174
**Parameters:**
175
- `prompt` (string, required): Image description
176
- `model` (string, optional): Image model (default: "flux")
177
- `width` (integer, optional): Width in pixels (default: 1024)
178
- `height` (integer, optional): Height in pixels (default: 1024)
179
180
**Example Request:**
181
```json
182
{
183
"jsonrpc": "2.0",
184
"id": 3,
185
"method": "tools/call",
186
"params": {
187
"name": "image_generation",
188
"arguments": {
189
"prompt": "A serene mountain landscape at sunset",
190
"width": 1024,
191
"height": 1024
192
}
193
}
194
}
195
```
196
197
**Example Usage in Claude:**
198
> "Generate an image of a serene mountain landscape at sunset"
199
200
## Integration Examples
201
202
### Python Script
203
204
```python
205
import asyncio
206
import json
207
from g4f.mcp.server import MCPServer, MCPRequest
208
209
async def search_web(query: str):
210
server = MCPServer()
211
request = MCPRequest(
212
jsonrpc="2.0",
213
id=1,
214
method="tools/call",
215
params={
216
"name": "web_search",
217
"arguments": {"query": query}
218
}
219
)
220
response = await server.handle_request(request)
221
return response.result
222
223
# Run it
224
result = asyncio.run(search_web("Python tutorials"))
225
print(result)
226
```
227
228
### Command Line Testing
229
230
```bash
231
# Test initialize
232
echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}' | g4f mcp
233
234
# Test list tools
235
echo '{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}' | g4f mcp
236
237
# Test web search
238
echo '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"web_search","arguments":{"query":"test"}}}' | g4f mcp
239
```
240
241
### Using with Shell Scripts
242
243
```bash
244
#!/bin/bash
245
# search.sh - Simple web search wrapper
246
247
query="$1"
248
request=$(cat <<EOF
249
{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"web_search","arguments":{"query":"$query"}}}
250
EOF
251
)
252
253
echo "$request" | python -m g4f.mcp | jq '.result.content[0].text | fromjson'
254
```
255
256
## Troubleshooting
257
258
### Server Won't Start
259
260
**Problem**: Server exits immediately or shows import errors
261
262
**Solution**:
263
```bash
264
# Install all dependencies
265
pip install -r requirements.txt
266
267
# Or install with all extras
268
pip install -U g4f[all]
269
```
270
271
### Tools Return Errors
272
273
**Problem**: Tools return error messages about missing packages
274
275
**Solution**: Install specific dependencies:
276
```bash
277
# For web search
278
pip install ddgs beautifulsoup4
279
280
# For web scraping
281
pip install aiohttp beautifulsoup4
282
283
# For image generation
284
pip install pillow
285
```
286
287
### Network Errors
288
289
**Problem**: Tools fail with connection errors
290
291
**Solution**:
292
- Check internet connectivity
293
- Some providers may be rate-limited
294
- Try different providers for image generation
295
- Check firewall settings
296
297
### Claude Desktop Not Finding Server
298
299
**Problem**: Claude doesn't show gpt4free tools
300
301
**Solution**:
302
1. Verify config file location and syntax
303
2. Check that Python is in PATH
304
3. Try absolute path to Python:
305
```json
306
{
307
"mcpServers": {
308
"gpt4free": {
309
"command": "/usr/bin/python3",
310
"args": ["-m", "g4f.mcp"]
311
}
312
}
313
}
314
```
315
4. Restart Claude Desktop completely
316
5. Check Claude logs for errors
317
318
### Debug Mode
319
320
Enable debug output:
321
```bash
322
# Redirect stderr to see debug messages
323
g4f mcp 2> mcp_debug.log
324
325
# Run with verbose output
326
g4f mcp --debug 2>&1 | tee mcp_output.log
327
```
328
329
### Verify Installation
330
331
Run the test script:
332
```bash
333
python etc/testing/test_mcp_server.py
334
```
335
336
Or the interactive demo:
337
```bash
338
python etc/testing/test_mcp_interactive.py
339
```
340
341
## Protocol Details
342
343
The MCP server implements JSON-RPC 2.0 over stdio transport.
344
345
**Supported Methods:**
346
- `initialize` - Initialize the connection
347
- `tools/list` - List all available tools
348
- `tools/call` - Execute a tool
349
- `ping` - Health check
350
351
**Message Format:**
352
- Requests: One JSON object per line on stdin
353
- Responses: One JSON object per line on stdout
354
- Logs: Messages on stderr
355
356
## Advanced Usage
357
358
### Custom Tool Development
359
360
To add custom tools, see `g4f/mcp/tools.py`:
361
362
```python
363
from g4f.mcp.tools import MCPTool
364
365
class MyCustomTool(MCPTool):
366
@property
367
def description(self) -> str:
368
return "My custom tool description"
369
370
@property
371
def input_schema(self) -> Dict[str, Any]:
372
return {
373
"type": "object",
374
"properties": {
375
"param1": {"type": "string", "description": "..."}
376
},
377
"required": ["param1"]
378
}
379
380
async def execute(self, arguments: Dict[str, Any]) -> Any:
381
# Your implementation
382
pass
383
```
384
385
Register in `g4f/mcp/server.py`:
386
```python
387
self.tools['my_tool'] = MyCustomTool()
388
```
389
390
## Support
391
392
- Documentation: [g4f/mcp/README.md](README.md)
393
- Issues: https://github.com/xtekky/gpt4free/issues
394
- MCP Specification: https://modelcontextprotocol.io/
395
396
## License
397
398
Part of the gpt4free project, licensed under GNU General Public License v3.0.
@@ -0,0 +1,201 @@
1
#!/usr/bin/env python
2
"""
3
Example: Using the MCP Server Tools
4
5
This script demonstrates how to interact with the MCP server tools programmatically.
6
It shows how each tool can be used and what kind of results to expect.
7
"""
8
9
import asyncio
10
import json
11
from g4f.mcp.server import MCPServer, MCPRequest
12
13
14
async def demo_web_search():
15
"""Demonstrate web search tool"""
16
print("\n" + "=" * 70)
17
print("DEMO: Web Search Tool")
18
print("=" * 70)
19
20
server = MCPServer()
21
22
# Create a tool call request for web search
23
request = MCPRequest(
24
jsonrpc="2.0",
25
id=1,
26
method="tools/call",
27
params={
28
"name": "web_search",
29
"arguments": {
30
"query": "Python programming tutorials",
31
"max_results": 3
32
}
33
}
34
)
35
36
print("\nRequest:")
37
print(json.dumps({
38
"method": "tools/call",
39
"params": request.params
40
}, indent=2))
41
42
print("\nExecuting web search...")
43
response = await server.handle_request(request)
44
45
if response.result:
46
print("\nSuccess! Response:")
47
content = response.result.get("content", [])
48
if content:
49
result_text = content[0].get("text", "")
50
result_data = json.loads(result_text)
51
print(json.dumps(result_data, indent=2))
52
elif response.error:
53
print(f"\nError: {response.error}")
54
55
56
async def demo_web_scrape():
57
"""Demonstrate web scraping tool"""
58
print("\n" + "=" * 70)
59
print("DEMO: Web Scrape Tool")
60
print("=" * 70)
61
62
server = MCPServer()
63
64
# Create a tool call request for web scraping
65
request = MCPRequest(
66
jsonrpc="2.0",
67
id=2,
68
method="tools/call",
69
params={
70
"name": "web_scrape",
71
"arguments": {
72
"url": "https://example.com",
73
"max_words": 200
74
}
75
}
76
)
77
78
print("\nRequest:")
79
print(json.dumps({
80
"method": "tools/call",
81
"params": request.params
82
}, indent=2))
83
84
print("\nExecuting web scrape...")
85
response = await server.handle_request(request)
86
87
if response.result:
88
print("\nSuccess! Response:")
89
content = response.result.get("content", [])
90
if content:
91
result_text = content[0].get("text", "")
92
result_data = json.loads(result_text)
93
print(json.dumps(result_data, indent=2))
94
elif response.error:
95
print(f"\nError: {response.error}")
96
97
98
async def demo_image_generation():
99
"""Demonstrate image generation tool"""
100
print("\n" + "=" * 70)
101
print("DEMO: Image Generation Tool")
102
print("=" * 70)
103
104
server = MCPServer()
105
106
# Create a tool call request for image generation
107
request = MCPRequest(
108
jsonrpc="2.0",
109
id=3,
110
method="tools/call",
111
params={
112
"name": "image_generation",
113
"arguments": {
114
"prompt": "A beautiful sunset over mountains",
115
"model": "flux",
116
"width": 512,
117
"height": 512
118
}
119
}
120
)
121
122
print("\nRequest:")
123
print(json.dumps({
124
"method": "tools/call",
125
"params": request.params
126
}, indent=2))
127
128
print("\nExecuting image generation...")
129
response = await server.handle_request(request)
130
131
if response.result:
132
print("\nSuccess! Response:")
133
content = response.result.get("content", [])
134
if content:
135
result_text = content[0].get("text", "")
136
result_data = json.loads(result_text)
137
# Don't print the full base64 image data, just show metadata
138
if "image" in result_data and result_data["image"].startswith("data:"):
139
result_data["image"] = result_data["image"][:100] + "... (base64 data truncated)"
140
print(json.dumps(result_data, indent=2))
141
elif response.error:
142
print(f"\nError: {response.error}")
143
144
145
async def main():
146
"""Run all demos"""
147
print("\n" + "=" * 70)
148
print("gpt4free MCP Server - Tool Demonstrations")
149
print("=" * 70)
150
print("\nThis script demonstrates the three main tools available in the MCP server:")
151
print("1. Web Search - Search the web using DuckDuckGo")
152
print("2. Web Scrape - Extract content from web pages")
153
print("3. Image Generation - Generate images from text prompts")
154
print("\nNote: These tools require network access and may fail in isolated environments.")
155
156
# Show tool information
157
print("\n" + "=" * 70)
158
print("Available Tools")
159
print("=" * 70)
160
161
server = MCPServer()
162
for name, tool in server.tools.items():
163
print(f"\n• {name}")
164
print(f" Description: {tool.description}")
165
schema = tool.input_schema
166
required = schema.get("required", [])
167
properties = schema.get("properties", {})
168
print(f" Required parameters: {', '.join(required)}")
169
print(f" Optional parameters: {', '.join([k for k in properties.keys() if k not in required])}")
170
171
# Run demos (these may fail without network access or required packages)
172
try:
173
await demo_web_search()
174
except Exception as e:
175
print(f"\n⚠ Web search demo failed: {e}")
176
print("This is expected without network access or required packages (ddgs, beautifulsoup4)")
177
178
try:
179
await demo_web_scrape()
180
except Exception as e:
181
print(f"\n⚠ Web scrape demo failed: {e}")
182
print("This is expected without network access or required packages (aiohttp, beautifulsoup4)")
183
184
try:
185
await demo_image_generation()
186
except Exception as e:
187
print(f"\n⚠ Image generation demo failed: {e}")
188
print("This is expected without network access or image generation providers")
189
190
print("\n" + "=" * 70)
191
print("Demo Complete")
192
print("=" * 70)
193
print("\nTo use these tools in production:")
194
print("1. Start the MCP server: g4f mcp")
195
print("2. Configure your AI assistant to connect to it")
196
print("3. The assistant can then use these tools to enhance its capabilities")
197
print("\nSee g4f/mcp/README.md for detailed configuration instructions.")
198
199
200
if __name__ == "__main__":
201
asyncio.run(main())