search1api-mcp 0.1.0 → 0.1.2

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 fatwang2
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,12 +1,36 @@
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
9
+ - Website sitemap extraction
8
10
  - Seamless integration with Claude Desktop
9
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
27
+
28
+ ### 3. Sitemap Tool
29
+ - Name: `sitemap`
30
+ - Description: Get all related links from a URL
31
+ - Parameters:
32
+ * `url` (required): URL to get sitemap
33
+
10
34
  ## Setup Guide
11
35
 
12
36
  ### 1. Get Search1API Key
@@ -21,9 +45,10 @@ Update your Claude configuration file (`claude_desktop_config.json`) with the fo
21
45
  {
22
46
  "mcpServers": {
23
47
  "search1api": {
24
- "command": "search1api-mcp",
48
+ "command": "npx",
49
+ "args": ["-y", "search1api-mcp"],
25
50
  "env": {
26
- "SEARCH1API_KEY": "your search1api key"
51
+ "SEARCH1API_KEY": "YOUR_SEARCH1API_KEY"
27
52
  }
28
53
  }
29
54
  }
@@ -34,6 +59,12 @@ Configuration file location:
34
59
  - macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
35
60
  - Windows: `%APPDATA%\Claude\claude_desktop_config.json`
36
61
 
62
+ ## Version History
63
+
64
+ - v0.1.2: Added sitemap functionality
65
+ - v0.1.1: Added web crawling functionality
66
+ - v0.1.0: Initial release with search functionality
67
+
37
68
  ## License
38
69
 
39
70
  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, isValidSitemapArgs } from "./types.js";
8
7
  dotenv.config();
9
8
  const API_KEY = process.env.SEARCH1API_KEY;
10
9
  if (!API_KEY) {
@@ -14,109 +13,190 @@ 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
+ SITEMAP: '/sitemap'
18
19
  }
19
20
  };
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: {}
21
+ const SEARCH_TOOL = {
22
+ name: "search",
23
+ description: "A fast way to search the world",
24
+ inputSchema: {
25
+ type: "object",
26
+ properties: {
27
+ query: {
28
+ type: "string",
29
+ description: "Search query"
30
+ },
31
+ max_results: {
32
+ type: "number",
33
+ description: "Maximum number of results to return (default: 10)",
34
+ default: 10
35
+ },
36
+ search_service: {
37
+ type: "string",
38
+ description: "Search service to use (default: google)",
39
+ default: "google"
31
40
  }
32
- });
33
- // Configure axios with defaults
34
- this.axiosInstance = axios.create({
35
- baseURL: API_CONFIG.BASE_URL,
41
+ },
42
+ required: ["query"]
43
+ }
44
+ };
45
+ const CRAWL_TOOL = {
46
+ name: "crawl",
47
+ description: "Extract content from URL",
48
+ inputSchema: {
49
+ type: "object",
50
+ properties: {
51
+ url: {
52
+ type: "string",
53
+ description: "URL to crawl"
54
+ }
55
+ },
56
+ required: ["url"]
57
+ }
58
+ };
59
+ const SITEMAP_TOOL = {
60
+ name: "sitemap",
61
+ description: "Get all related links from a URL",
62
+ inputSchema: {
63
+ type: "object",
64
+ properties: {
65
+ url: {
66
+ type: "string",
67
+ description: "URL to get sitemap"
68
+ }
69
+ },
70
+ required: ["url"]
71
+ }
72
+ };
73
+ // Server implementation
74
+ const server = new Server({
75
+ name: "search1api-mcp",
76
+ version: "0.1.0",
77
+ }, {
78
+ capabilities: {
79
+ resources: {},
80
+ tools: {},
81
+ },
82
+ });
83
+ // 添加服务器事件监听
84
+ server.onerror = (error) => {
85
+ log('MCP Server Error:', error);
86
+ };
87
+ server.onclose = () => {
88
+ log('MCP Server Connection Closed');
89
+ };
90
+ // 添加异步请求函数
91
+ async function makeRequest(endpoint, data) {
92
+ const startTime = Date.now();
93
+ // 确保 BASE_URL 末尾没有斜杠,endpoint 开头有斜杠
94
+ const baseUrl = API_CONFIG.BASE_URL.replace(/\/+$/, '');
95
+ const path = endpoint.startsWith('/') ? endpoint : `/${endpoint}`;
96
+ const url = `${baseUrl}${path}`;
97
+ log(`Starting request to ${url}`);
98
+ try {
99
+ const controller = new AbortController();
100
+ const timeoutId = setTimeout(() => controller.abort(), 30000); // 30 seconds timeout
101
+ const response = await fetch(url, {
102
+ method: 'POST',
36
103
  headers: {
37
104
  'Authorization': `Bearer ${API_KEY}`,
38
- 'Content-Type': 'application/json'
39
- }
105
+ 'Content-Type': 'application/json',
106
+ },
107
+ body: JSON.stringify(data),
108
+ signal: controller.signal
40
109
  });
41
- this.setupHandlers();
42
- this.setupErrorHandling();
110
+ clearTimeout(timeoutId);
111
+ if (!response.ok) {
112
+ const errorData = await response.json().catch(() => ({}));
113
+ throw new Error(`API error: ${response.status} ${errorData.message || response.statusText}`);
114
+ }
115
+ const result = await response.json();
116
+ const endTime = Date.now();
117
+ log(`Request completed in ${endTime - startTime}ms`);
118
+ return result;
43
119
  }
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
- });
120
+ catch (error) {
121
+ const endTime = Date.now();
122
+ log(`Request failed after ${endTime - startTime}ms:`, error);
123
+ if (error instanceof Error) {
124
+ if (error.name === 'AbortError') {
125
+ throw new Error('Request timeout after 30 seconds');
126
+ }
127
+ // 添加更多网络错误的详细信息
128
+ const networkError = error;
129
+ if (networkError.code) {
130
+ throw new Error(`Network error (${networkError.code}): ${networkError.message}`);
131
+ }
132
+ }
133
+ throw error;
52
134
  }
53
- setupHandlers() {
54
- this.setupResourceHandlers();
55
- this.setupToolHandlers();
135
+ }
136
+ // 添加错误处理工具函数
137
+ function formatError(error) {
138
+ if (error instanceof Error) {
139
+ return error.message;
56
140
  }
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}"`,
141
+ return String(error);
142
+ }
143
+ // Resource handlers
144
+ server.setRequestHandler(ListResourcesRequestSchema, async () => ({
145
+ resources: [{
146
+ uri: `search://${encodeURIComponent(API_CONFIG.DEFAULT_QUERY)}`,
147
+ name: `Search results for "${API_CONFIG.DEFAULT_QUERY}"`,
148
+ mimeType: "application/json",
149
+ description: "Search results including title, link, and snippet"
150
+ }]
151
+ }));
152
+ server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
153
+ const defaultQuery = API_CONFIG.DEFAULT_QUERY;
154
+ if (request.params.uri !== `search://${encodeURIComponent(defaultQuery)}`) {
155
+ throw new McpError(ErrorCode.InvalidRequest, `Unknown resource: ${request.params.uri}`);
156
+ }
157
+ try {
158
+ const response = await makeRequest(API_CONFIG.ENDPOINTS.SEARCH, {
159
+ query: defaultQuery,
160
+ search_service: "google",
161
+ max_results: 10
162
+ });
163
+ return {
164
+ contents: [{
165
+ uri: request.params.uri,
62
166
  mimeType: "application/json",
63
- description: "Search results including title, link, and snippet"
167
+ text: JSON.stringify(response.results, null, 2)
64
168
  }]
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
- });
169
+ };
92
170
  }
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, {
171
+ catch (error) {
172
+ log("Search error:", error);
173
+ return {
174
+ contents: [{
175
+ uri: request.params.uri,
176
+ mimeType: "text/plain",
177
+ text: `Search API error: ${formatError(error)}`
178
+ }],
179
+ isError: true
180
+ };
181
+ }
182
+ });
183
+ // Tool handlers
184
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
185
+ tools: [SEARCH_TOOL, CRAWL_TOOL, SITEMAP_TOOL],
186
+ }));
187
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
188
+ try {
189
+ const { name, arguments: args } = request.params;
190
+ if (!args) {
191
+ throw new Error("No arguments provided");
192
+ }
193
+ switch (name) {
194
+ case "search": {
195
+ if (!isValidSearchArgs(args)) {
196
+ throw new McpError(ErrorCode.InvalidParams, "Invalid search arguments");
197
+ }
198
+ const { query, max_results = 10, search_service = "google" } = args;
199
+ const response = await makeRequest(API_CONFIG.ENDPOINTS.SEARCH, {
120
200
  query,
121
201
  search_service,
122
202
  max_results
@@ -125,30 +205,94 @@ class SearchServer {
125
205
  content: [{
126
206
  type: "text",
127
207
  mimeType: "application/json",
128
- text: JSON.stringify(response.data.results, null, 2)
208
+ text: JSON.stringify(response.results, null, 2)
129
209
  }]
130
210
  };
131
211
  }
132
- catch (error) {
133
- if (axios.isAxiosError(error)) {
212
+ case "crawl": {
213
+ if (!isValidCrawlArgs(args)) {
214
+ throw new McpError(ErrorCode.InvalidParams, "Invalid crawl arguments");
215
+ }
216
+ const { url } = args;
217
+ log("Starting crawl for:", url);
218
+ try {
219
+ const startTime = Date.now();
220
+ const response = await makeRequest(API_CONFIG.ENDPOINTS.CRAWL, { url });
221
+ const endTime = Date.now();
222
+ log(`Crawl completed successfully in ${endTime - startTime}ms`);
223
+ return {
224
+ content: [{
225
+ type: "text",
226
+ mimeType: "application/json",
227
+ text: JSON.stringify(response.results, null, 2)
228
+ }]
229
+ };
230
+ }
231
+ catch (error) {
232
+ log("Crawl error:", error);
134
233
  return {
135
234
  content: [{
136
235
  type: "text",
137
236
  mimeType: "text/plain",
138
- text: `Search API error: ${error.response?.data?.message ?? error.message}`
237
+ text: `Crawl API error: ${formatError(error)}`
139
238
  }],
140
239
  isError: true
141
240
  };
142
241
  }
143
- throw error;
144
242
  }
145
- });
243
+ case "sitemap": {
244
+ if (!isValidSitemapArgs(args)) {
245
+ throw new McpError(ErrorCode.InvalidParams, "Invalid sitemap arguments");
246
+ }
247
+ try {
248
+ const response = await makeRequest(API_CONFIG.ENDPOINTS.SITEMAP, args);
249
+ return {
250
+ content: [{
251
+ type: "text",
252
+ mimeType: "application/json",
253
+ text: JSON.stringify(response.links, null, 2)
254
+ }]
255
+ };
256
+ }
257
+ catch (error) {
258
+ throw formatError(error);
259
+ }
260
+ }
261
+ default:
262
+ throw new McpError(ErrorCode.MethodNotFound, `Unknown tool: ${name}`);
263
+ }
146
264
  }
147
- async run() {
148
- const transport = new StdioServerTransport();
149
- await this.server.connect(transport);
150
- console.error("Search1API MCP server running on stdio");
265
+ catch (error) {
266
+ log("Tool error:", error);
267
+ return {
268
+ content: [{
269
+ type: "text",
270
+ mimeType: "text/plain",
271
+ text: `API error: ${formatError(error)}`
272
+ }],
273
+ isError: true
274
+ };
151
275
  }
276
+ });
277
+ // 添加日志工具函数
278
+ function log(message, ...args) {
279
+ const timestamp = new Date().toISOString();
280
+ console.error(`[${timestamp}] ${message}`, ...args);
281
+ }
282
+ async function runServer() {
283
+ const transport = new StdioServerTransport();
284
+ log("Starting Search1API MCP Server...");
285
+ // 添加全局错误处理
286
+ process.on('uncaughtException', (error) => {
287
+ log('Uncaught Exception:', error);
288
+ });
289
+ process.on('unhandledRejection', (reason, promise) => {
290
+ log('Unhandled Rejection at:', promise, 'reason:', reason);
291
+ });
292
+ await server.connect(transport);
293
+ log("Search1API MCP Server running on stdio");
152
294
  }
153
- const server = new SearchServer();
154
- server.run().catch(console.error);
295
+ runServer().catch((error) => {
296
+ log('Fatal error running server:', error);
297
+ process.exit(1);
298
+ });
package/build/types.js CHANGED
@@ -14,3 +14,23 @@ 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
+ }
27
+ export function isValidSitemapArgs(args) {
28
+ if (typeof args !== 'object' || args === null) {
29
+ return false;
30
+ }
31
+ const { url } = args;
32
+ if (typeof url !== 'string' || url.trim().length === 0) {
33
+ return false;
34
+ }
35
+ return true;
36
+ }
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.2",
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",