search1api-mcp 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,11 +1,29 @@
1
1
  # Search1API MCP Server
2
2
 
3
- A Model Context Protocol (MCP) server that provides search functionality using Search1API.
3
+ A Model Context Protocol (MCP) server that provides search and crawl functionality using Search1API.
4
4
 
5
5
  ## Features
6
6
 
7
7
  - Web search functionality through Search1API
8
+ - Web page content extraction (crawling)
8
9
  - Seamless integration with Claude Desktop
10
+ - Support for Google search engine
11
+
12
+ ## Tools
13
+
14
+ ### 1. Search Tool
15
+ - Name: `search`
16
+ - Description: Search the web using Search1API
17
+ - Parameters:
18
+ * `query` (required): Search query
19
+ * `max_results` (optional, default: 10): Number of results to return
20
+ * `search_service` (optional, default: "google"): Search service to use
21
+
22
+ ### 2. Crawl Tool
23
+ - Name: `crawl`
24
+ - Description: Extract content from a URL using Search1API
25
+ - Parameters:
26
+ * `url` (required): URL to crawl
9
27
 
10
28
  ## Setup Guide
11
29
 
@@ -21,9 +39,10 @@ Update your Claude configuration file (`claude_desktop_config.json`) with the fo
21
39
  {
22
40
  "mcpServers": {
23
41
  "search1api": {
24
- "command": "search1api-mcp",
42
+ "command": "npx",
43
+ "args": ["-y", "search1api-mcp"],
25
44
  "env": {
26
- "SEARCH1API_KEY": "your search1api key"
45
+ "SEARCH1API_KEY": "YOUR_SEARCH1API_KEY"
27
46
  }
28
47
  }
29
48
  }
@@ -34,6 +53,11 @@ Configuration file location:
34
53
  - macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
35
54
  - Windows: `%APPDATA%\Claude\claude_desktop_config.json`
36
55
 
56
+ ## Version History
57
+
58
+ - v0.1.1: Added web crawling functionality
59
+ - v0.1.0: Initial release with search functionality
60
+
37
61
  ## License
38
62
 
39
63
  This project is licensed under the MIT License - see the LICENSE file for details.
package/build/index.js CHANGED
@@ -2,9 +2,8 @@
2
2
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
3
3
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
4
  import { ListResourcesRequestSchema, ReadResourceRequestSchema, ListToolsRequestSchema, CallToolRequestSchema, ErrorCode, McpError } from "@modelcontextprotocol/sdk/types.js";
5
- import axios from "axios";
6
5
  import dotenv from "dotenv";
7
- import { isValidSearchArgs } from "./types.js";
6
+ import { isValidSearchArgs, isValidCrawlArgs } from "./types.js";
8
7
  dotenv.config();
9
8
  const API_KEY = process.env.SEARCH1API_KEY;
10
9
  if (!API_KEY) {
@@ -14,109 +13,175 @@ const API_CONFIG = {
14
13
  BASE_URL: 'https://api.search1api.com',
15
14
  DEFAULT_QUERY: 'latest news in the world',
16
15
  ENDPOINTS: {
17
- SEARCH: 'search'
16
+ SEARCH: '/search',
17
+ CRAWL: '/crawl'
18
18
  }
19
19
  };
20
- class SearchServer {
21
- server;
22
- axiosInstance;
23
- constructor() {
24
- this.server = new Server({
25
- name: "search1api-mcp",
26
- version: "0.1.0"
27
- }, {
28
- capabilities: {
29
- resources: {},
30
- tools: {}
20
+ const SEARCH_TOOL = {
21
+ name: "search",
22
+ description: "A fast way to search the world",
23
+ inputSchema: {
24
+ type: "object",
25
+ properties: {
26
+ query: {
27
+ type: "string",
28
+ description: "Search query"
29
+ },
30
+ max_results: {
31
+ type: "number",
32
+ description: "Maximum number of results to return (default: 10)",
33
+ default: 10
34
+ },
35
+ search_service: {
36
+ type: "string",
37
+ description: "Search service to use (default: google)",
38
+ default: "google"
31
39
  }
32
- });
33
- // Configure axios with defaults
34
- this.axiosInstance = axios.create({
35
- baseURL: API_CONFIG.BASE_URL,
40
+ },
41
+ required: ["query"]
42
+ }
43
+ };
44
+ const CRAWL_TOOL = {
45
+ name: "crawl",
46
+ description: "Crawl and extract content from a specific URL",
47
+ inputSchema: {
48
+ type: "object",
49
+ properties: {
50
+ url: {
51
+ type: "string",
52
+ description: "URL to crawl"
53
+ }
54
+ },
55
+ required: ["url"]
56
+ }
57
+ };
58
+ // Server implementation
59
+ const server = new Server({
60
+ name: "search1api-mcp",
61
+ version: "0.1.0",
62
+ }, {
63
+ capabilities: {
64
+ resources: {},
65
+ tools: {},
66
+ },
67
+ });
68
+ // 添加服务器事件监听
69
+ server.onerror = (error) => {
70
+ log('MCP Server Error:', error);
71
+ };
72
+ server.onclose = () => {
73
+ log('MCP Server Connection Closed');
74
+ };
75
+ // 添加异步请求函数
76
+ async function makeRequest(endpoint, data) {
77
+ const startTime = Date.now();
78
+ // 确保 BASE_URL 末尾没有斜杠,endpoint 开头有斜杠
79
+ const baseUrl = API_CONFIG.BASE_URL.replace(/\/+$/, '');
80
+ const path = endpoint.startsWith('/') ? endpoint : `/${endpoint}`;
81
+ const url = `${baseUrl}${path}`;
82
+ log(`Starting request to ${url}`);
83
+ try {
84
+ const controller = new AbortController();
85
+ const timeoutId = setTimeout(() => controller.abort(), 30000); // 30 seconds timeout
86
+ const response = await fetch(url, {
87
+ method: 'POST',
36
88
  headers: {
37
89
  'Authorization': `Bearer ${API_KEY}`,
38
- 'Content-Type': 'application/json'
39
- }
90
+ 'Content-Type': 'application/json',
91
+ },
92
+ body: JSON.stringify(data),
93
+ signal: controller.signal
40
94
  });
41
- this.setupHandlers();
42
- this.setupErrorHandling();
95
+ clearTimeout(timeoutId);
96
+ if (!response.ok) {
97
+ const errorData = await response.json().catch(() => ({}));
98
+ throw new Error(`API error: ${response.status} ${errorData.message || response.statusText}`);
99
+ }
100
+ const result = await response.json();
101
+ const endTime = Date.now();
102
+ log(`Request completed in ${endTime - startTime}ms`);
103
+ return result;
43
104
  }
44
- setupErrorHandling() {
45
- this.server.onerror = (error) => {
46
- console.error("[MCP Error]", error);
47
- };
48
- process.on('SIGINT', async () => {
49
- await this.server.close();
50
- process.exit(0);
51
- });
105
+ catch (error) {
106
+ const endTime = Date.now();
107
+ log(`Request failed after ${endTime - startTime}ms:`, error);
108
+ if (error instanceof Error) {
109
+ if (error.name === 'AbortError') {
110
+ throw new Error('Request timeout after 30 seconds');
111
+ }
112
+ // 添加更多网络错误的详细信息
113
+ const networkError = error;
114
+ if (networkError.code) {
115
+ throw new Error(`Network error (${networkError.code}): ${networkError.message}`);
116
+ }
117
+ }
118
+ throw error;
119
+ }
120
+ }
121
+ // 添加错误处理工具函数
122
+ function formatError(error) {
123
+ if (error instanceof Error) {
124
+ return error.message;
52
125
  }
53
- setupHandlers() {
54
- this.setupResourceHandlers();
55
- this.setupToolHandlers();
126
+ return String(error);
127
+ }
128
+ // Resource handlers
129
+ server.setRequestHandler(ListResourcesRequestSchema, async () => ({
130
+ resources: [{
131
+ uri: `search://${encodeURIComponent(API_CONFIG.DEFAULT_QUERY)}`,
132
+ name: `Search results for "${API_CONFIG.DEFAULT_QUERY}"`,
133
+ mimeType: "application/json",
134
+ description: "Search results including title, link, and snippet"
135
+ }]
136
+ }));
137
+ server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
138
+ const defaultQuery = API_CONFIG.DEFAULT_QUERY;
139
+ if (request.params.uri !== `search://${encodeURIComponent(defaultQuery)}`) {
140
+ throw new McpError(ErrorCode.InvalidRequest, `Unknown resource: ${request.params.uri}`);
56
141
  }
57
- setupResourceHandlers() {
58
- this.server.setRequestHandler(ListResourcesRequestSchema, async () => ({
59
- resources: [{
60
- uri: `search://${encodeURIComponent(API_CONFIG.DEFAULT_QUERY)}`,
61
- name: `Search results for "${API_CONFIG.DEFAULT_QUERY}"`,
142
+ try {
143
+ const response = await makeRequest(API_CONFIG.ENDPOINTS.SEARCH, {
144
+ query: defaultQuery,
145
+ search_service: "google",
146
+ max_results: 10
147
+ });
148
+ return {
149
+ contents: [{
150
+ uri: request.params.uri,
62
151
  mimeType: "application/json",
63
- description: "Search results including title, link, and snippet"
152
+ text: JSON.stringify(response.results, null, 2)
64
153
  }]
65
- }));
66
- this.server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
67
- const defaultQuery = API_CONFIG.DEFAULT_QUERY;
68
- if (request.params.uri !== `search://${encodeURIComponent(defaultQuery)}`) {
69
- throw new McpError(ErrorCode.InvalidRequest, `Unknown resource: ${request.params.uri}`);
70
- }
71
- try {
72
- const response = await this.axiosInstance.post(API_CONFIG.ENDPOINTS.SEARCH, {
73
- query: defaultQuery,
74
- search_service: "google",
75
- max_results: 10
76
- });
77
- return {
78
- contents: [{
79
- uri: request.params.uri,
80
- mimeType: "application/json",
81
- text: JSON.stringify(response.data.results, null, 2)
82
- }]
83
- };
84
- }
85
- catch (error) {
86
- if (axios.isAxiosError(error)) {
87
- throw new McpError(ErrorCode.InternalError, `Search API error: ${error.response?.data?.message ?? error.message}`);
88
- }
89
- throw error;
90
- }
91
- });
154
+ };
92
155
  }
93
- setupToolHandlers() {
94
- this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
95
- tools: [{
96
- name: "search1api",
97
- description: "Search for information using Search1API service",
98
- inputSchema: {
99
- type: "object",
100
- properties: {
101
- query: {
102
- type: "string",
103
- description: "Search query"
104
- }
105
- },
106
- required: ["query"]
107
- }
108
- }]
109
- }));
110
- this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
111
- if (request.params.name !== "search1api") {
112
- throw new McpError(ErrorCode.MethodNotFound, `Unknown tool: ${request.params.name}`);
113
- }
114
- if (!isValidSearchArgs(request.params.arguments)) {
115
- throw new McpError(ErrorCode.InvalidParams, "Invalid search arguments");
116
- }
117
- const { query, max_results = 10, search_service = "google" } = request.params.arguments;
118
- try {
119
- const response = await this.axiosInstance.post(API_CONFIG.ENDPOINTS.SEARCH, {
156
+ catch (error) {
157
+ log("Search error:", error);
158
+ return {
159
+ contents: [{
160
+ uri: request.params.uri,
161
+ mimeType: "text/plain",
162
+ text: `Search API error: ${formatError(error)}`
163
+ }],
164
+ isError: true
165
+ };
166
+ }
167
+ });
168
+ // Tool handlers
169
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
170
+ tools: [SEARCH_TOOL, CRAWL_TOOL],
171
+ }));
172
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
173
+ try {
174
+ const { name, arguments: args } = request.params;
175
+ if (!args) {
176
+ throw new Error("No arguments provided");
177
+ }
178
+ switch (name) {
179
+ case "search": {
180
+ if (!isValidSearchArgs(args)) {
181
+ throw new McpError(ErrorCode.InvalidParams, "Invalid search arguments");
182
+ }
183
+ const { query, max_results = 10, search_service = "google" } = args;
184
+ const response = await makeRequest(API_CONFIG.ENDPOINTS.SEARCH, {
120
185
  query,
121
186
  search_service,
122
187
  max_results
@@ -125,30 +190,76 @@ class SearchServer {
125
190
  content: [{
126
191
  type: "text",
127
192
  mimeType: "application/json",
128
- text: JSON.stringify(response.data.results, null, 2)
193
+ text: JSON.stringify(response.results, null, 2)
129
194
  }]
130
195
  };
131
196
  }
132
- catch (error) {
133
- if (axios.isAxiosError(error)) {
197
+ case "crawl": {
198
+ if (!isValidCrawlArgs(args)) {
199
+ throw new McpError(ErrorCode.InvalidParams, "Invalid crawl arguments");
200
+ }
201
+ const { url } = args;
202
+ log("Starting crawl for:", url);
203
+ try {
204
+ const startTime = Date.now();
205
+ const response = await makeRequest(API_CONFIG.ENDPOINTS.CRAWL, { url });
206
+ const endTime = Date.now();
207
+ log(`Crawl completed successfully in ${endTime - startTime}ms`);
208
+ return {
209
+ content: [{
210
+ type: "text",
211
+ mimeType: "application/json",
212
+ text: JSON.stringify(response.results, null, 2)
213
+ }]
214
+ };
215
+ }
216
+ catch (error) {
217
+ log("Crawl error:", error);
134
218
  return {
135
219
  content: [{
136
220
  type: "text",
137
221
  mimeType: "text/plain",
138
- text: `Search API error: ${error.response?.data?.message ?? error.message}`
222
+ text: `Crawl API error: ${formatError(error)}`
139
223
  }],
140
224
  isError: true
141
225
  };
142
226
  }
143
- throw error;
144
227
  }
145
- });
228
+ default:
229
+ throw new McpError(ErrorCode.MethodNotFound, `Unknown tool: ${name}`);
230
+ }
146
231
  }
147
- async run() {
148
- const transport = new StdioServerTransport();
149
- await this.server.connect(transport);
150
- console.error("Search1API MCP server running on stdio");
232
+ catch (error) {
233
+ log("Tool error:", error);
234
+ return {
235
+ content: [{
236
+ type: "text",
237
+ mimeType: "text/plain",
238
+ text: `API error: ${formatError(error)}`
239
+ }],
240
+ isError: true
241
+ };
151
242
  }
243
+ });
244
+ // 添加日志工具函数
245
+ function log(message, ...args) {
246
+ const timestamp = new Date().toISOString();
247
+ console.error(`[${timestamp}] ${message}`, ...args);
248
+ }
249
+ async function runServer() {
250
+ const transport = new StdioServerTransport();
251
+ log("Starting Search1API MCP Server...");
252
+ // 添加全局错误处理
253
+ process.on('uncaughtException', (error) => {
254
+ log('Uncaught Exception:', error);
255
+ });
256
+ process.on('unhandledRejection', (reason, promise) => {
257
+ log('Unhandled Rejection at:', promise, 'reason:', reason);
258
+ });
259
+ await server.connect(transport);
260
+ log("Search1API MCP Server running on stdio");
152
261
  }
153
- const server = new SearchServer();
154
- server.run().catch(console.error);
262
+ runServer().catch((error) => {
263
+ log('Fatal error running server:', error);
264
+ process.exit(1);
265
+ });
package/build/types.js CHANGED
@@ -14,3 +14,13 @@ export function isValidSearchArgs(args) {
14
14
  }
15
15
  return true;
16
16
  }
17
+ export function isValidCrawlArgs(args) {
18
+ if (typeof args !== 'object' || args === null) {
19
+ return false;
20
+ }
21
+ const { url } = args;
22
+ if (typeof url !== 'string' || url.trim().length === 0) {
23
+ return false;
24
+ }
25
+ return true;
26
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "search1api-mcp",
3
- "version": "0.1.0",
4
- "description": "A Model Context Protocol (MCP) server that provides search functionality using Search1API",
3
+ "version": "0.1.1",
4
+ "description": "A Model Context Protocol (MCP) server that provides search and crawl functionality using Search1API",
5
5
  "private": false,
6
6
  "type": "module",
7
7
  "bin": {
@@ -29,6 +29,8 @@
29
29
  "mcp",
30
30
  "claude",
31
31
  "search",
32
+ "crawl",
33
+ "google",
32
34
  "search1api"
33
35
  ],
34
36
  "author": "fatwang2",