search1api-mcp 0.1.8 → 0.3.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
@@ -2,79 +2,114 @@
2
2
 
3
3
  [中文文档](./README_zh.md)
4
4
 
5
- A Model Context Protocol (MCP) server that provides search and crawl functionality using Search1API.
5
+ The official MCP server for [Search1API](https://www.search1api.com/?utm_source=mcp) — web search, news, crawling, and more in one API.
6
6
 
7
- https://github.com/user-attachments/assets/58bc98ae-3b6b-442c-a7fc-010508b5f028
7
+ ## Authentication
8
8
 
9
- More discussions and updates, please follow our official [X](https://x.com/search1api), or join the official [discord](https://discord.com/invite/AKXYq32Bxc)
9
+ - OAuth-aware clients can connect to the Remote MCP URL directly, then sign in and approve access in the browser.
10
+ - Existing integrations can continue to use an API key from the [Search1API dashboard](https://dashboard.search1api.com).
10
11
 
11
- ## Features
12
+ ## Quick Start (Remote MCP)
12
13
 
13
- - Web search functionality
14
- - News search functionality
15
- - Web page content extraction
16
- - Website sitemap extraction
17
- - Deep thinking and complex problem solving with DeepSeek R1
18
- - Seamless integration with Claude Desktop, Cursor, Windsurf, Cline and other MCP clients
14
+ No installation required. Configure your MCP client with the remote URL. Use OAuth when the client supports it, or provide an API key.
19
15
 
20
- ## Tools
16
+ ### Authentication
17
+
18
+ Three methods are supported — use whichever your client supports:
19
+
20
+ | Method | Format |
21
+ |--------|--------|
22
+ | OAuth 2.1 | Connect to `https://mcp.search1api.com/mcp` without a key and follow the client sign-in flow |
23
+ | Authorization Header | `Authorization: Bearer YOUR_SEARCH1API_KEY` |
24
+ | URL Query Parameter (legacy) | `https://mcp.search1api.com/mcp?apiKey=YOUR_SEARCH1API_KEY` |
25
+
26
+ Prefer OAuth or the Authorization header. Query-parameter credentials can be exposed in URLs, logs, and shell history.
27
+
28
+ ### Claude Desktop
29
+
30
+ ```json
31
+ {
32
+ "mcpServers": {
33
+ "search1api": {
34
+ "url": "https://mcp.search1api.com/mcp",
35
+ "headers": {
36
+ "Authorization": "Bearer YOUR_SEARCH1API_KEY"
37
+ }
38
+ }
39
+ }
40
+ }
41
+ ```
42
+
43
+ ### Claude.ai (Web)
44
+
45
+ Settings > Connectors > Add custom connector:
46
+
47
+ ```
48
+ https://mcp.search1api.com/mcp?apiKey=YOUR_SEARCH1API_KEY
49
+ ```
50
+
51
+ ### Cursor
52
+
53
+ ```json
54
+ {
55
+ "mcpServers": {
56
+ "search1api": {
57
+ "url": "https://mcp.search1api.com/mcp",
58
+ "headers": {
59
+ "Authorization": "Bearer YOUR_SEARCH1API_KEY"
60
+ }
61
+ }
62
+ }
63
+ }
64
+ ```
21
65
 
22
- ### 1. Search Tool
23
- - Name: `search`
24
- - Description: Search the web using Search1API
25
- - Parameters:
26
- * `query` (required): Search query in natural language. Be specific and concise for better results
27
- * `max_results` (optional, default: 10): Number of results to return
28
- * `search_service` (optional, default: "google"): Search service to use (google, bing, duckduckgo, yahoo, x, reddit, github, youtube, arxiv, wechat, bilibili, imdb, wikipedia)
29
- * `crawl_results` (optional, default: 0): Number of results to crawl for full webpage content
30
- * `include_sites` (optional): List of sites to include in search
31
- * `exclude_sites` (optional): List of sites to exclude from search
32
- * `time_range` (optional): Time range for search results ("day", "month", "year")
33
-
34
- ### 2. News Tool
35
- - Name: `news`
36
- - Description: Search for news articles using Search1API
37
- - Parameters:
38
- * `query` (required): Search query in natural language. Be specific and concise for better results
39
- * `max_results` (optional, default: 10): Number of results to return
40
- * `search_service` (optional, default: "bing"): Search service to use (google, bing, duckduckgo, yahoo, hackernews)
41
- * `crawl_results` (optional, default: 0): Number of results to crawl for full webpage content
42
- * `include_sites` (optional): List of sites to include in search
43
- * `exclude_sites` (optional): List of sites to exclude from search
44
- * `time_range` (optional): Time range for search results ("day", "month", "year")
45
-
46
- ### 3. Crawl Tool
47
- - Name: `crawl`
48
- - Description: Extract content from a URL using Search1API
49
- - Parameters:
50
- * `url` (required): URL to crawl
51
-
52
- ### 4. Sitemap Tool
53
- - Name: `sitemap`
54
- - Description: Get all related links from a URL
55
- - Parameters:
56
- * `url` (required): URL to get sitemap
57
-
58
- ### 5. Reasoning Tool
59
- - Name: `reasoning`
60
- - Description: A tool for deep thinking and complex problem solving with fast deepseek r1 model and web search ability(You can change to any other model in search1api website but the speed is not guaranteed)
61
- - Parameters:
62
- * `content` (required): The question or problem that needs deep thinking
63
-
64
- ### 6. Trending Tool
65
- - Name: `trending`
66
- - Description: Get trending topics from popular platforms
67
- - Parameters:
68
- * `search_service` (required): Specify the platform to get trending topics from (github, hackernews)
69
- * `max_results` (optional, default: 10): Maximum number of trending items to return
70
-
71
- ## Setup Guide
72
-
73
- ### 1. Get Search1API Key
74
- 1. Register at [Search1API](https://www.search1api.com/?utm_source=mcp)
75
- 2. Get your api key and 100 free credits
76
-
77
- ### 2. Configure
66
+ ### VS Code
67
+
68
+ ```json
69
+ {
70
+ "servers": {
71
+ "search1api": {
72
+ "type": "http",
73
+ "url": "https://mcp.search1api.com/mcp",
74
+ "headers": {
75
+ "Authorization": "Bearer YOUR_SEARCH1API_KEY"
76
+ }
77
+ }
78
+ }
79
+ }
80
+ ```
81
+
82
+ ### Claude Code
83
+
84
+ ```bash
85
+ claude mcp add --transport http search1api https://mcp.search1api.com/mcp \
86
+ --header "Authorization: Bearer YOUR_SEARCH1API_KEY"
87
+ ```
88
+
89
+ ### Windsurf
90
+
91
+ ```json
92
+ {
93
+ "mcpServers": {
94
+ "search1api": {
95
+ "serverUrl": "https://mcp.search1api.com/mcp?apiKey=YOUR_SEARCH1API_KEY"
96
+ }
97
+ }
98
+ }
99
+ ```
100
+
101
+ ## Agent Skill
102
+
103
+ The Agent Skill has moved to [search1api-cli](https://github.com/superagents-lab/search1api-cli). Install it with:
104
+
105
+ ```bash
106
+ npm install -g search1api-cli
107
+ npx skills add superagents-lab/search1api-cli
108
+ ```
109
+
110
+ ## Local Mode (stdio)
111
+
112
+ If you prefer to run the server locally, use npx — no cloning required:
78
113
 
79
114
  ```json
80
115
  {
@@ -90,18 +125,70 @@ More discussions and updates, please follow our official [X](https://x.com/searc
90
125
  }
91
126
  ```
92
127
 
128
+ ## Tools
129
+
130
+ ### search
131
+ Search the web using Search1API.
132
+
133
+ | Parameter | Required | Default | Description |
134
+ |-----------|----------|---------|-------------|
135
+ | `query` | Yes | - | Search query |
136
+ | `max_results` | No | 10 | Number of results |
137
+ | `search_service` | No | google | google, bing, duckduckgo, yahoo, x, reddit, github, youtube, arxiv, wechat, bilibili, imdb, wikipedia |
138
+ | `crawl_results` | No | 0 | Number of results to crawl for full content |
139
+ | `include_sites` | No | [] | Sites to include |
140
+ | `exclude_sites` | No | [] | Sites to exclude |
141
+ | `time_range` | No | - | day, month, year |
142
+
143
+ ### news
144
+ Search for news articles.
145
+
146
+ | Parameter | Required | Default | Description |
147
+ |-----------|----------|---------|-------------|
148
+ | `query` | Yes | - | Search query |
149
+ | `max_results` | No | 10 | Number of results |
150
+ | `search_service` | No | bing | google, bing, duckduckgo, yahoo, hackernews |
151
+ | `crawl_results` | No | 0 | Number of results to crawl for full content |
152
+ | `include_sites` | No | [] | Sites to include |
153
+ | `exclude_sites` | No | [] | Sites to exclude |
154
+ | `time_range` | No | - | day, month, year |
155
+
156
+ ### crawl
157
+ Extract content from a URL.
158
+
159
+ | Parameter | Required | Description |
160
+ |-----------|----------|-------------|
161
+ | `url` | Yes | URL to crawl |
162
+
163
+ ### sitemap
164
+ Get all related links from a URL.
165
+
166
+ | Parameter | Required | Description |
167
+ |-----------|----------|-------------|
168
+ | `url` | Yes | URL to get sitemap |
169
+
170
+ ### trending
171
+ Get trending topics from popular platforms.
172
+
173
+ | Parameter | Required | Default | Description |
174
+ |-----------|----------|---------|-------------|
175
+ | `search_service` | Yes | - | github, hackernews |
176
+ | `max_results` | No | 10 | Number of items |
177
+
93
178
  ## Version History
94
179
 
95
- - v0.1.8: Added X(Twitter) and Reddit search services
96
- - v0.1.7: Added Trending tool for GitHub and Hacker News
97
- - v0.1.6: Added Wikipedia search service
98
- - v0.1.5: Added new search parameters (include_sites, exclude_sites, time_range) and new search services (arxiv, wechat, bilibili, imdb)
99
- - v0.1.4: Added reasoning tool with deepseek r1 and updated the Cursor and Windsurf configuration guide
100
- - v0.1.3: Added news search functionality
101
- - v0.1.2: Added sitemap functionality
102
- - v0.1.1: Added web crawling functionality
103
- - v0.1.0: Initial release with search functionality
180
+ - v0.3.1: OAuth 2.1 support for Remote MCP; retired reasoning tool removed
181
+ - v0.3.0: Remote MCP support via Streamable HTTP; per-session API key authentication
182
+ - v0.2.0: Fallback `.env` support for LibreChat integration
183
+ - v0.1.8: X (Twitter) and Reddit search services
184
+ - v0.1.7: Trending tool for GitHub and Hacker News
185
+ - v0.1.6: Wikipedia search service
186
+ - v0.1.5: New search parameters and services (arxiv, wechat, bilibili, imdb)
187
+ - v0.1.3: News search
188
+ - v0.1.2: Sitemap
189
+ - v0.1.1: Web crawling
190
+ - v0.1.0: Initial release
104
191
 
105
192
  ## License
106
193
 
107
- This project is licensed under the MIT License - see the LICENSE file for details.
194
+ MIT
package/build/api.js CHANGED
@@ -4,24 +4,35 @@ import { log } from './utils.js';
4
4
  * Unified API request function
5
5
  * @param endpoint API endpoint
6
6
  * @param data Request data
7
+ * @param apiKey Optional per-session API key (falls back to global API_KEY)
7
8
  * @returns API response
8
9
  */
9
- export async function makeRequest(endpoint, data) {
10
+ export async function makeRequest(endpoint, data, apiKey) {
11
+ const key = apiKey || API_KEY;
12
+ if (!key) {
13
+ throw new Error("API key is required. Provide SEARCH1API_KEY or pass apiKey per-session.");
14
+ }
10
15
  const startTime = Date.now();
11
16
  const baseUrl = API_CONFIG.BASE_URL.replace(/\/+$/, '');
12
17
  const path = endpoint.startsWith('/') ? endpoint : `/${endpoint}`;
13
18
  const url = `${baseUrl}${path}`;
19
+ // Debug log for request details (excluding sensitive info)
20
+ log(`Making request to: ${url}`);
21
+ log(`Request data: ${JSON.stringify(data, null, 2)}`);
14
22
  try {
15
23
  const response = await fetch(url, {
16
24
  method: 'POST',
17
25
  headers: {
18
- 'Authorization': `Bearer ${API_KEY}`,
26
+ 'Authorization': `Bearer ${key}`,
19
27
  'Content-Type': 'application/json',
20
28
  },
21
29
  body: JSON.stringify(data)
22
30
  });
31
+ // Log response status only
32
+ log(`Response status: ${response.status}`);
23
33
  if (!response.ok) {
24
34
  const errorData = await response.json().catch(() => ({}));
35
+ log(`Error response: ${JSON.stringify(errorData, null, 2)}`);
25
36
  throw new Error(`API error: ${response.status} ${errorData.message || response.statusText}`);
26
37
  }
27
38
  const result = await response.json();
package/build/config.js CHANGED
@@ -1,9 +1,36 @@
1
1
  import dotenv from "dotenv";
2
- dotenv.config();
3
- // Check API key
4
- const API_KEY = process.env.SEARCH1API_KEY;
2
+ import { fileURLToPath } from 'url';
3
+ import { dirname, join } from 'path';
4
+ import { log } from './utils.js';
5
+ // Check API key directly from environment variables first
6
+ let API_KEY = process.env.SEARCH1API_KEY;
7
+ log(`Attempting to read SEARCH1API_KEY from environment: ${API_KEY ? 'Found' : 'Not found'}`);
8
+ // If not found in env, try loading from .env file in project root as fallback
5
9
  if (!API_KEY) {
6
- throw new Error("SEARCH1API_KEY environment variable is required");
10
+ log('SEARCH1API_KEY not found in environment, attempting to load from .env file in project root...');
11
+ const __filename = fileURLToPath(import.meta.url);
12
+ const __dirname = dirname(__filename);
13
+ // Path relative to the build directory (build/config.js) to reach project root
14
+ const projectRootEnvPath = join(__dirname, '../.env');
15
+ log(`Attempting to load .env from: ${projectRootEnvPath}`);
16
+ const result = dotenv.config({ path: projectRootEnvPath });
17
+ if (result.error) {
18
+ log(`Failed to load .env from ${projectRootEnvPath}: ${result.error.message}`);
19
+ }
20
+ else if (result.parsed && result.parsed.SEARCH1API_KEY) {
21
+ API_KEY = result.parsed.SEARCH1API_KEY;
22
+ log(`Successfully loaded SEARCH1API_KEY from ${projectRootEnvPath}`);
23
+ }
24
+ else {
25
+ log(`.env file found at ${projectRootEnvPath}, but SEARCH1API_KEY was not inside.`);
26
+ }
27
+ }
28
+ // Final check
29
+ if (!API_KEY) {
30
+ log('SEARCH1API_KEY not found. Stdio mode requires it; HTTP mode uses per-session keys.');
31
+ }
32
+ else {
33
+ log('API key located successfully.');
7
34
  }
8
35
  // API configuration
9
36
  export const API_CONFIG = {
@@ -14,7 +41,6 @@ export const API_CONFIG = {
14
41
  CRAWL: '/crawl',
15
42
  SITEMAP: '/sitemap',
16
43
  NEWS: '/news',
17
- REASONING: '/v1/chat/completions',
18
44
  TRENDING: '/trending'
19
45
  }
20
46
  };
package/build/http.js ADDED
@@ -0,0 +1,239 @@
1
+ #!/usr/bin/env node
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
4
+ import express from "express";
5
+ import { createMcpServer } from "./server.js";
6
+ import { log } from "./utils.js";
7
+ const app = express();
8
+ const API_BASE_URL = process.env.SEARCH1API_API_URL || "https://api.search1api.com";
9
+ const AUTHORIZATION_SERVER = "https://clerk.search1api.com";
10
+ const MCP_RESOURCE = "https://mcp.search1api.com/mcp";
11
+ const MCP_RESOURCE_METADATA = "https://mcp.search1api.com/.well-known/oauth-protected-resource/mcp";
12
+ // The service root is documentation, not an MCP transport endpoint. Keep
13
+ // query parameters so bookmarked campaign/support links remain attributable.
14
+ app.get("/", (req, res) => {
15
+ const target = new URL("https://www.search1api.com/docs/integrations/mcp");
16
+ for (const [key, value] of Object.entries(req.query)) {
17
+ if (typeof value === "string") {
18
+ target.searchParams.append(key, value);
19
+ }
20
+ }
21
+ res.redirect(301, target.toString());
22
+ });
23
+ const protectedResourceMetadata = {
24
+ resource: MCP_RESOURCE,
25
+ authorization_servers: [AUTHORIZATION_SERVER],
26
+ bearer_methods_supported: ["header"],
27
+ scopes_supported: ["openid", "offline_access"],
28
+ resource_documentation: "https://www.search1api.com/auth.md",
29
+ };
30
+ app.get([
31
+ "/.well-known/oauth-protected-resource",
32
+ "/.well-known/oauth-protected-resource/mcp",
33
+ ], (_req, res) => {
34
+ res.type("application/json").json(protectedResourceMetadata);
35
+ });
36
+ app.get("/.well-known/oauth-authorization-server", (_req, res) => {
37
+ res.redirect(302, `${AUTHORIZATION_SERVER}/.well-known/oauth-authorization-server`);
38
+ });
39
+ app.use(express.json());
40
+ // Session storage: sessionId -> MCP transport, server, and authenticated
41
+ // principal. The credential itself is mutable so a refreshed OAuth access
42
+ // token can continue the same session after it is validated.
43
+ const sessions = new Map();
44
+ /** Extract a Bearer credential, retaining the legacy query-key fallback. */
45
+ function extractCredential(req) {
46
+ const auth = req.headers.authorization;
47
+ if (auth?.startsWith("Bearer ")) {
48
+ return auth.slice(7).trim() || undefined;
49
+ }
50
+ const queryKey = req.query.apiKey;
51
+ if (typeof queryKey === "string" && queryKey.trim()) {
52
+ return queryKey.trim();
53
+ }
54
+ return undefined;
55
+ }
56
+ function challenge(res, message, error) {
57
+ const errorParameter = error ? `, error="${error}"` : "";
58
+ res.set("WWW-Authenticate", `Bearer resource_metadata="${MCP_RESOURCE_METADATA}"${errorParameter}`);
59
+ res.status(401).json({
60
+ jsonrpc: "2.0",
61
+ error: { code: -32001, message },
62
+ id: null,
63
+ });
64
+ }
65
+ /** Validate both Clerk OAuth tokens and legacy Search1API API keys at the API. */
66
+ async function validateCredential(credential) {
67
+ const response = await fetch(`${API_BASE_URL}/usage`, {
68
+ headers: { Authorization: `Bearer ${credential}` },
69
+ });
70
+ if (response.status === 401 || response.status === 403) {
71
+ return null;
72
+ }
73
+ if (!response.ok) {
74
+ throw new Error(`Search1API credential validation returned ${response.status}`);
75
+ }
76
+ const identity = (await response.json());
77
+ let principal;
78
+ if (identity.credential_type === "oauth" &&
79
+ identity.user_id &&
80
+ identity.client_id) {
81
+ principal = `oauth:${identity.user_id}:${identity.client_id}`;
82
+ }
83
+ else {
84
+ principal = `api-key:${createHash("sha256")
85
+ .update(credential)
86
+ .digest("hex")}`;
87
+ }
88
+ return { credential, principal };
89
+ }
90
+ async function authenticateMcpRequest(req, res, expectedPrincipal) {
91
+ const credential = extractCredential(req);
92
+ if (!credential) {
93
+ challenge(res, "Authentication is required. Use OAuth 2.1 discovery or provide a Search1API API key as a Bearer token.");
94
+ return null;
95
+ }
96
+ let authenticated;
97
+ try {
98
+ authenticated = await validateCredential(credential);
99
+ }
100
+ catch (error) {
101
+ log("Credential validation failed:", error);
102
+ res.status(503).json({
103
+ jsonrpc: "2.0",
104
+ error: {
105
+ code: -32002,
106
+ message: "Search1API authentication is temporarily unavailable.",
107
+ },
108
+ id: null,
109
+ });
110
+ return null;
111
+ }
112
+ if (!authenticated) {
113
+ challenge(res, "The Bearer credential is invalid or expired.", "invalid_token");
114
+ return null;
115
+ }
116
+ if (expectedPrincipal && authenticated.principal !== expectedPrincipal) {
117
+ res.status(403).json({
118
+ jsonrpc: "2.0",
119
+ error: {
120
+ code: -32003,
121
+ message: "The credential does not belong to this MCP session.",
122
+ },
123
+ id: null,
124
+ });
125
+ return null;
126
+ }
127
+ return authenticated;
128
+ }
129
+ function isInitializeRequest(body) {
130
+ if (Array.isArray(body)) {
131
+ return body.some((message) => typeof message === "object" &&
132
+ message !== null &&
133
+ message.method === "initialize");
134
+ }
135
+ return (typeof body === "object" &&
136
+ body !== null &&
137
+ body.method === "initialize");
138
+ }
139
+ // Handle POST /mcp - initialize or route to an existing session.
140
+ app.post("/mcp", async (req, res) => {
141
+ const sessionId = req.headers["mcp-session-id"];
142
+ if (sessionId && sessions.has(sessionId)) {
143
+ const session = sessions.get(sessionId);
144
+ const authenticated = await authenticateMcpRequest(req, res, session.principal);
145
+ if (!authenticated) {
146
+ return;
147
+ }
148
+ session.credential.current = authenticated.credential;
149
+ await session.transport.handleRequest(req, res, req.body);
150
+ return;
151
+ }
152
+ if (!sessionId && isInitializeRequest(req.body)) {
153
+ const authenticated = await authenticateMcpRequest(req, res);
154
+ if (!authenticated) {
155
+ return;
156
+ }
157
+ const credential = { current: authenticated.credential };
158
+ const transport = new StreamableHTTPServerTransport({
159
+ sessionIdGenerator: () => randomUUID(),
160
+ onsessioninitialized: (sid) => {
161
+ sessions.set(sid, {
162
+ transport,
163
+ server,
164
+ principal: authenticated.principal,
165
+ credential,
166
+ });
167
+ log(`Session created: ${sid}`);
168
+ },
169
+ });
170
+ transport.onclose = () => {
171
+ if (transport.sessionId) {
172
+ sessions.delete(transport.sessionId);
173
+ log(`Session closed: ${transport.sessionId}`);
174
+ }
175
+ };
176
+ const server = createMcpServer(() => credential.current);
177
+ await server.connect(transport);
178
+ await transport.handleRequest(req, res, req.body);
179
+ return;
180
+ }
181
+ res.status(400).json({
182
+ jsonrpc: "2.0",
183
+ error: {
184
+ code: -32600,
185
+ message: "Bad request: no valid session or not an initialize request",
186
+ },
187
+ id: null,
188
+ });
189
+ });
190
+ // Handle GET /mcp - SSE stream for an existing session.
191
+ app.get("/mcp", async (req, res) => {
192
+ const sessionId = req.headers["mcp-session-id"];
193
+ if (!sessionId || !sessions.has(sessionId)) {
194
+ res.status(400).json({
195
+ jsonrpc: "2.0",
196
+ error: { code: -32600, message: "Invalid or missing session ID" },
197
+ id: null,
198
+ });
199
+ return;
200
+ }
201
+ const session = sessions.get(sessionId);
202
+ const authenticated = await authenticateMcpRequest(req, res, session.principal);
203
+ if (!authenticated) {
204
+ return;
205
+ }
206
+ session.credential.current = authenticated.credential;
207
+ await session.transport.handleRequest(req, res);
208
+ });
209
+ // Handle DELETE /mcp - authenticated session termination.
210
+ app.delete("/mcp", async (req, res) => {
211
+ const sessionId = req.headers["mcp-session-id"];
212
+ if (sessionId && sessions.has(sessionId)) {
213
+ const session = sessions.get(sessionId);
214
+ const authenticated = await authenticateMcpRequest(req, res, session.principal);
215
+ if (!authenticated) {
216
+ return;
217
+ }
218
+ await session.transport.handleRequest(req, res);
219
+ await session.server.close();
220
+ sessions.delete(sessionId);
221
+ log(`Session terminated: ${sessionId}`);
222
+ return;
223
+ }
224
+ res.status(400).json({
225
+ jsonrpc: "2.0",
226
+ error: { code: -32600, message: "Invalid or missing session ID" },
227
+ id: null,
228
+ });
229
+ });
230
+ const PORT = parseInt(process.env.PORT || "3000", 10);
231
+ app.listen(PORT, () => {
232
+ log(`Search1API MCP HTTP server listening on http://localhost:${PORT}/mcp`);
233
+ });
234
+ process.on("uncaughtException", (error) => {
235
+ log("Uncaught exception:", error);
236
+ });
237
+ process.on("unhandledRejection", (reason) => {
238
+ log("Unhandled rejection:", reason);
239
+ });
package/build/index.js CHANGED
@@ -1,45 +1,46 @@
1
1
  #!/usr/bin/env node
2
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
2
3
  import { log } from "./utils.js";
3
- import { createServer } from "./server.js";
4
+ import { createMcpServer } from "./server.js";
4
5
  import { API_KEY } from "./config.js";
5
6
  /**
6
- * Main function - Program entry point
7
+ * Main function - Program entry point (stdio mode)
7
8
  */
8
9
  async function main() {
9
- // Ensure API key exists
10
+ // Stdio mode requires API key at startup
10
11
  if (!API_KEY) {
11
12
  log("SEARCH1API_KEY environment variable is not set");
12
13
  process.exit(1);
13
14
  }
14
15
  try {
15
- log("Starting Search1API MCP server");
16
- const server = createServer();
17
- // Start server
18
- await server.start();
16
+ log("Starting Search1API MCP server (stdio mode)");
17
+ const server = createMcpServer();
18
+ const transport = new StdioServerTransport();
19
+ await server.connect(transport);
19
20
  log("Server started successfully");
20
21
  // Handle process exit signals
21
- setupExitHandlers(server);
22
+ const exitHandler = async () => {
23
+ log("Shutting down server...");
24
+ await server.close();
25
+ process.exit(0);
26
+ };
27
+ process.on("SIGINT", exitHandler);
28
+ process.on("SIGTERM", exitHandler);
29
+ process.on("SIGUSR1", exitHandler);
30
+ process.on("SIGUSR2", exitHandler);
22
31
  }
23
32
  catch (error) {
24
33
  log("Failed to start server:", error);
25
34
  process.exit(1);
26
35
  }
27
36
  }
28
- /**
29
- * Set up process exit signal handlers
30
- */
31
- function setupExitHandlers(server) {
32
- const exitHandler = async () => {
33
- log("Shutting down server...");
34
- await server.stop();
35
- process.exit(0);
36
- };
37
- // Handle various exit signals
38
- process.on("SIGINT", exitHandler);
39
- process.on("SIGTERM", exitHandler);
40
- process.on("SIGUSR1", exitHandler);
41
- process.on("SIGUSR2", exitHandler);
42
- }
37
+ // Handle global errors
38
+ process.on("uncaughtException", (error) => {
39
+ log("Uncaught exception:", error);
40
+ });
41
+ process.on("unhandledRejection", (reason) => {
42
+ log("Unhandled rejection:", reason);
43
+ });
43
44
  // Start program
44
45
  main().catch((error) => {
45
46
  log("Fatal error:", error);
package/build/server.js CHANGED
@@ -1,50 +1,30 @@
1
1
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
2
  import { McpError, ErrorCode, CallToolRequestSchema, ListResourcesRequestSchema, ReadResourceRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
4
3
  import { handleToolCall } from "./tools/handlers.js";
5
4
  import { log, formatError } from "./utils.js";
6
5
  import { handleListResources, handleReadResource } from "./resources.js";
7
6
  import { ALL_TOOLS } from "./tools/index.js";
7
+ import { PACKAGE_VERSION } from "./version.js";
8
8
  /**
9
9
  * Create and configure MCP server
10
+ * @param credential Optional per-session credential or mutable credential
11
+ * provider (used in HTTP mode so refreshed OAuth tokens can replace expired
12
+ * access tokens without changing the MCP session principal)
13
+ * @returns Server instance ready to be connected to a transport
10
14
  */
11
- export function createServer() {
15
+ export function createMcpServer(credential) {
12
16
  log("Creating Search1API MCP server");
13
- // Create server instance
14
17
  const server = new Server({
15
18
  name: "search1api-server",
16
- version: "1.0.0"
19
+ version: PACKAGE_VERSION
17
20
  }, {
18
21
  capabilities: {
19
22
  resources: {},
20
23
  tools: {}
21
24
  }
22
25
  });
23
- // Set up request handlers
24
- setupRequestHandlers(server);
25
- // Create STDIO transport
26
- const transport = new StdioServerTransport();
27
- return {
28
- start: async () => {
29
- try {
30
- await server.connect(transport);
31
- log("Server started successfully");
32
- }
33
- catch (error) {
34
- log("Failed to start server:", error);
35
- throw error;
36
- }
37
- },
38
- stop: async () => {
39
- try {
40
- await server.close();
41
- log("Server stopped");
42
- }
43
- catch (error) {
44
- log("Error stopping server:", error);
45
- }
46
- }
47
- };
26
+ setupRequestHandlers(server, credential);
27
+ return server;
48
28
  }
49
29
  /**
50
30
  * Helper function to handle errors uniformly
@@ -59,14 +39,15 @@ function handleError(context, error) {
59
39
  /**
60
40
  * Set up server request handlers
61
41
  */
62
- function setupRequestHandlers(server) {
42
+ function setupRequestHandlers(server, credential) {
63
43
  // Handle tool calls
64
44
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
65
45
  try {
66
46
  const toolName = request.params.name;
67
47
  const toolArgs = request.params.arguments;
68
48
  log(`Tool call received: ${toolName}`);
69
- return await handleToolCall(toolName, toolArgs);
49
+ const bearerCredential = typeof credential === "function" ? credential() : credential;
50
+ return await handleToolCall(toolName, toolArgs, bearerCredential);
70
51
  }
71
52
  catch (error) {
72
53
  handleError("handling tool call", error);
@@ -102,11 +83,4 @@ function setupRequestHandlers(server) {
102
83
  server.setRequestHandler(ListToolsRequestSchema, async () => {
103
84
  return { tools: ALL_TOOLS };
104
85
  });
105
- // Handle global errors
106
- process.on("uncaughtException", (error) => {
107
- log("Uncaught exception:", error);
108
- });
109
- process.on("unhandledRejection", (reason) => {
110
- log("Unhandled rejection:", reason);
111
- });
112
86
  }
@@ -6,7 +6,7 @@ import { McpError, ErrorCode } from "@modelcontextprotocol/sdk/types.js";
6
6
  /**
7
7
  * Implementation of the crawl tool
8
8
  */
9
- export async function handleCrawl(args) {
9
+ export async function handleCrawl(args, apiKey) {
10
10
  if (!isValidCrawlArgs(args)) {
11
11
  throw new McpError(ErrorCode.InvalidParams, "Invalid crawl arguments");
12
12
  }
@@ -14,7 +14,7 @@ export async function handleCrawl(args) {
14
14
  log("Starting crawl for:", url);
15
15
  try {
16
16
  const startTime = Date.now();
17
- const response = await makeRequest(API_CONFIG.ENDPOINTS.CRAWL, { url });
17
+ const response = await makeRequest(API_CONFIG.ENDPOINTS.CRAWL, { url }, apiKey);
18
18
  const endTime = Date.now();
19
19
  log(`Crawl completed successfully in ${endTime - startTime}ms`);
20
20
  return {
@@ -4,30 +4,28 @@ import { handleSearch } from './search.js';
4
4
  import { handleCrawl } from './crawl.js';
5
5
  import { handleSitemap } from './sitemap.js';
6
6
  import { handleNews } from './news.js';
7
- import { handleReasoning } from './reasoning.js';
8
7
  import { handleTrending } from './trending.js';
9
- import { SEARCH_TOOL, CRAWL_TOOL, SITEMAP_TOOL, NEWS_TOOL, REASONING_TOOL, TRENDING_TOOL } from './index.js';
8
+ import { SEARCH_TOOL, CRAWL_TOOL, SITEMAP_TOOL, NEWS_TOOL, TRENDING_TOOL } from './index.js';
10
9
  /**
11
10
  * Dispatch request based on tool name
12
11
  * @param toolName Name of the tool
13
12
  * @param args Tool parameters
13
+ * @param apiKey Optional per-session API key
14
14
  * @returns Tool processing result
15
15
  */
16
- export async function handleToolCall(toolName, args) {
16
+ export async function handleToolCall(toolName, args, apiKey) {
17
17
  log(`Handling tool call: ${toolName}`);
18
18
  switch (toolName) {
19
19
  case SEARCH_TOOL.name:
20
- return await handleSearch(args);
20
+ return await handleSearch(args, apiKey);
21
21
  case CRAWL_TOOL.name:
22
- return await handleCrawl(args);
22
+ return await handleCrawl(args, apiKey);
23
23
  case SITEMAP_TOOL.name:
24
- return await handleSitemap(args);
24
+ return await handleSitemap(args, apiKey);
25
25
  case NEWS_TOOL.name:
26
- return await handleNews(args);
27
- case REASONING_TOOL.name:
28
- return await handleReasoning(args);
26
+ return await handleNews(args, apiKey);
29
27
  case TRENDING_TOOL.name:
30
- return await handleTrending(args);
28
+ return await handleTrending(args, apiKey);
31
29
  default:
32
30
  log(`Unknown tool: ${toolName}`);
33
31
  throw new McpError(ErrorCode.InvalidParams, `Unknown tool: ${toolName}`);
@@ -132,21 +132,6 @@ export const SITEMAP_TOOL = {
132
132
  required: ["url"]
133
133
  }
134
134
  };
135
- // Reasoning tool definition
136
- export const REASONING_TOOL = {
137
- name: "reasoning",
138
- description: "Deep thinking and complex problem solving",
139
- inputSchema: {
140
- type: "object",
141
- properties: {
142
- content: {
143
- type: "string",
144
- description: "The question or problem that needs deep thinking"
145
- }
146
- },
147
- required: ["content"]
148
- }
149
- };
150
135
  // Trending tool definition
151
136
  export const TRENDING_TOOL = {
152
137
  name: "trending",
@@ -175,6 +160,5 @@ export const ALL_TOOLS = [
175
160
  NEWS_TOOL,
176
161
  CRAWL_TOOL,
177
162
  SITEMAP_TOOL,
178
- REASONING_TOOL,
179
163
  TRENDING_TOOL
180
164
  ];
@@ -6,13 +6,13 @@ import { McpError, ErrorCode } from "@modelcontextprotocol/sdk/types.js";
6
6
  /**
7
7
  * Implementation of the news search tool
8
8
  */
9
- export async function handleNews(args) {
9
+ export async function handleNews(args, apiKey) {
10
10
  if (!isValidNewsArgs(args)) {
11
11
  throw new McpError(ErrorCode.InvalidParams, "Invalid news search arguments");
12
12
  }
13
13
  log("Processing news search with query:", args.query);
14
14
  try {
15
- const response = await makeRequest(API_CONFIG.ENDPOINTS.NEWS, args);
15
+ const response = await makeRequest(API_CONFIG.ENDPOINTS.NEWS, args, apiKey);
16
16
  return {
17
17
  content: [{
18
18
  type: "text",
@@ -6,12 +6,12 @@ import { McpError, ErrorCode } from "@modelcontextprotocol/sdk/types.js";
6
6
  /**
7
7
  * Implementation of the search tool
8
8
  */
9
- export async function handleSearch(args) {
9
+ export async function handleSearch(args, apiKey) {
10
10
  if (!isValidSearchArgs(args)) {
11
11
  throw new McpError(ErrorCode.InvalidParams, "Invalid search arguments");
12
12
  }
13
13
  try {
14
- const response = await makeRequest(API_CONFIG.ENDPOINTS.SEARCH, args);
14
+ const response = await makeRequest(API_CONFIG.ENDPOINTS.SEARCH, args, apiKey);
15
15
  return {
16
16
  content: [{
17
17
  type: "text",
@@ -6,12 +6,12 @@ import { McpError, ErrorCode } from "@modelcontextprotocol/sdk/types.js";
6
6
  /**
7
7
  * Implementation of the sitemap tool
8
8
  */
9
- export async function handleSitemap(args) {
9
+ export async function handleSitemap(args, apiKey) {
10
10
  if (!isValidSitemapArgs(args)) {
11
11
  throw new McpError(ErrorCode.InvalidParams, "Invalid sitemap arguments");
12
12
  }
13
13
  try {
14
- const response = await makeRequest(API_CONFIG.ENDPOINTS.SITEMAP, args);
14
+ const response = await makeRequest(API_CONFIG.ENDPOINTS.SITEMAP, args, apiKey);
15
15
  return {
16
16
  content: [{
17
17
  type: "text",
@@ -6,12 +6,12 @@ import { McpError, ErrorCode } from "@modelcontextprotocol/sdk/types.js";
6
6
  /**
7
7
  * Implementation of the trending tool
8
8
  */
9
- export async function handleTrending(args) {
9
+ export async function handleTrending(args, apiKey) {
10
10
  if (!isValidTrendingArgs(args)) {
11
11
  throw new McpError(ErrorCode.InvalidParams, "Invalid trending arguments");
12
12
  }
13
13
  try {
14
- const response = await makeRequest(API_CONFIG.ENDPOINTS.TRENDING, args);
14
+ const response = await makeRequest(API_CONFIG.ENDPOINTS.TRENDING, args, apiKey);
15
15
  return {
16
16
  content: [{
17
17
  type: "text",
package/build/types.js CHANGED
@@ -116,16 +116,6 @@ export function isValidNewsArgs(args) {
116
116
  }
117
117
  return true;
118
118
  }
119
- export function isValidReasoningArgs(args) {
120
- if (typeof args !== 'object' || args === null) {
121
- return false;
122
- }
123
- const { content } = args;
124
- if (typeof content !== 'string' || content.trim().length === 0) {
125
- return false;
126
- }
127
- return true;
128
- }
129
119
  export var TrendingService;
130
120
  (function (TrendingService) {
131
121
  TrendingService["GITHUB"] = "github";
@@ -0,0 +1,4 @@
1
+ import { createRequire } from "node:module";
2
+ const require = createRequire(import.meta.url);
3
+ const packageJson = require("../package.json");
4
+ export const PACKAGE_VERSION = packageJson.version;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "search1api-mcp",
3
- "version": "0.1.8",
3
+ "version": "0.3.1",
4
4
  "description": "A Model Context Protocol (MCP) server that provides search and crawl functionality using Search1API",
5
5
  "private": false,
6
6
  "type": "module",
@@ -11,19 +11,23 @@
11
11
  "build"
12
12
  ],
13
13
  "scripts": {
14
- "build": "tsc && node -e \"require('fs').chmodSync('build/index.js', '755')\"",
15
- "prepare": "npm run build",
14
+ "build": "node -e \"require('node:fs').rmSync('build', { recursive: true, force: true })\" && tsc && node -e \"require('node:fs').chmodSync('build/index.js', '755')\"",
15
+ "test": "npm run build && node --test tests/*.test.mjs",
16
+ "start": "node build/http.js",
17
+ "prepack": "npm run build",
16
18
  "watch": "tsc --watch",
17
- "inspector": "npx @modelcontextprotocol/inspector build/index.js"
19
+ "inspector": "npx @modelcontextprotocol/inspector build/index.js",
20
+ "start:http": "node build/http.js"
18
21
  },
19
22
  "dependencies": {
20
- "@modelcontextprotocol/sdk": "^1.7.0",
21
- "axios": "^1.7.8",
22
- "dotenv": "^16.4.5"
23
+ "@modelcontextprotocol/sdk": "^1.29.0",
24
+ "dotenv": "^16.6.1",
25
+ "express": "^4.22.2"
23
26
  },
24
27
  "devDependencies": {
25
- "@types/node": "^20.11.24",
26
- "typescript": "^5.3.3"
28
+ "@types/express": "^5.0.6",
29
+ "@types/node": "^20.19.43",
30
+ "typescript": "^5.9.3"
27
31
  },
28
32
  "keywords": [
29
33
  "mcp",
@@ -33,11 +37,18 @@
33
37
  "google",
34
38
  "search1api"
35
39
  ],
36
- "author": "fatwang2",
40
+ "author": "Search1API",
37
41
  "license": "MIT",
38
42
  "repository": {
39
43
  "type": "git",
40
- "url": "git+https://github.com/fatwang2/search1api-mcp.git"
44
+ "url": "git+https://github.com/superagents-lab/search1api-mcp.git"
45
+ },
46
+ "homepage": "https://github.com/superagents-lab/search1api-mcp#readme",
47
+ "bugs": {
48
+ "url": "https://github.com/superagents-lab/search1api-mcp/issues"
49
+ },
50
+ "publishConfig": {
51
+ "access": "public"
41
52
  },
42
53
  "engines": {
43
54
  "node": ">=18.0.0"
@@ -1,56 +0,0 @@
1
- import { isValidReasoningArgs } from '../types.js';
2
- import { makeRequest } from '../api.js';
3
- import { formatError, log } from '../utils.js';
4
- import { API_CONFIG } from '../config.js';
5
- import { McpError, ErrorCode } from "@modelcontextprotocol/sdk/types.js";
6
- /**
7
- * Implementation of the deep thinking and complex reasoning tool
8
- */
9
- export async function handleReasoning(args) {
10
- if (!isValidReasoningArgs(args)) {
11
- throw new McpError(ErrorCode.InvalidParams, "Invalid reasoning arguments");
12
- }
13
- const { content } = args;
14
- log("Processing reasoning request");
15
- try {
16
- /**
17
- * Implementation of the deep thinking and complex reasoning tool
18
- */
19
- // Convert to API required format
20
- const apiRequestData = {
21
- model: "deepseek-r1-70b-fast-online",
22
- messages: [
23
- {
24
- role: "user",
25
- content: content
26
- }
27
- ],
28
- stream: false
29
- };
30
- // Use the correct structure of ReasoningResponse
31
- const response = await makeRequest(API_CONFIG.ENDPOINTS.REASONING, apiRequestData // Using converted format instead of raw args
32
- );
33
- // Directly use the correct structure of ReasoningResponse
34
- const resultText = response.choices && response.choices.length > 0
35
- ? response.choices[0].message.content
36
- : JSON.stringify(response);
37
- return {
38
- content: [{
39
- type: "text",
40
- mimeType: "text/plain",
41
- text: resultText
42
- }]
43
- };
44
- }
45
- catch (error) {
46
- log("Reasoning API error:", error);
47
- return {
48
- content: [{
49
- type: "text",
50
- mimeType: "text/plain",
51
- text: `Reasoning API error: ${formatError(error)}`
52
- }],
53
- isError: true
54
- };
55
- }
56
- }