search1api-mcp 0.3.1 → 0.5.0

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,7 +2,7 @@
2
2
 
3
3
  [中文文档](./README_zh.md)
4
4
 
5
- The official MCP server for [Search1API](https://www.search1api.com/?utm_source=mcp) — web search, news, crawling, and more in one API.
5
+ The official MCP server for [Search1API](https://www.search1api.com/?utm_source=mcp) — web search, news, page retrieval, sitemap discovery, and trending topics in one API.
6
6
 
7
7
  ## Authentication
8
8
 
@@ -109,7 +109,7 @@ npx skills add superagents-lab/search1api-cli
109
109
 
110
110
  ## Local Mode (stdio)
111
111
 
112
- If you prefer to run the server locally, use npx — no cloning required:
112
+ If you prefer to run the server locally, use Node.js 20 or newer with npx — no cloning required:
113
113
 
114
114
  ```json
115
115
  {
@@ -125,21 +125,35 @@ If you prefer to run the server locally, use npx — no cloning required:
125
125
  }
126
126
  ```
127
127
 
128
+ For self-hosted HTTP deployments behind a proxy, add any internal hostnames
129
+ that reach the Node.js process to the comma-separated `MCP_ALLOWED_HOSTS`
130
+ environment variable. `mcp.search1api.com` and localhost addresses are allowed
131
+ by default.
132
+
128
133
  ## Tools
129
134
 
130
135
  ### search
131
- Search the web using Search1API.
136
+ Search the web using Search1API. Results use the standard citable
137
+ `id`/`title`/`url` shape expected by ChatGPT deep research and company
138
+ knowledge.
132
139
 
133
140
  | Parameter | Required | Default | Description |
134
141
  |-----------|----------|---------|-------------|
135
142
  | `query` | Yes | - | Search query |
136
143
  | `max_results` | No | 10 | Number of results |
137
144
  | `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 |
145
+ | `crawl_results` | No | 0 | Number of top results to crawl for full content; each successful crawl adds 1 credit to the base 1-credit search request |
139
146
  | `include_sites` | No | [] | Sites to include |
140
147
  | `exclude_sites` | No | [] | Sites to exclude |
141
148
  | `time_range` | No | - | day, month, year |
142
149
 
150
+ ### fetch
151
+ Retrieve the full readable contents of a result returned by `search`.
152
+
153
+ | Parameter | Required | Description |
154
+ |-----------|----------|-------------|
155
+ | `id` | Yes | Result ID returned by `search` (the canonical page URL) |
156
+
143
157
  ### news
144
158
  Search for news articles.
145
159
 
@@ -148,7 +162,7 @@ Search for news articles.
148
162
  | `query` | Yes | - | Search query |
149
163
  | `max_results` | No | 10 | Number of results |
150
164
  | `search_service` | No | bing | google, bing, duckduckgo, yahoo, hackernews |
151
- | `crawl_results` | No | 0 | Number of results to crawl for full content |
165
+ | `crawl_results` | No | 0 | Number of top results to crawl for full content; each successful crawl adds 1 credit to the base 1-credit news request |
152
166
  | `include_sites` | No | [] | Sites to include |
153
167
  | `exclude_sites` | No | [] | Sites to exclude |
154
168
  | `time_range` | No | - | day, month, year |
@@ -177,6 +191,8 @@ Get trending topics from popular platforms.
177
191
 
178
192
  ## Version History
179
193
 
194
+ - v0.5.0: MCP 2026-07-28 support with automatic protocol negotiation; stateless compatibility for 2025-era HTTP clients; request-level authentication
195
+ - v0.4.0: Standard `search`/`fetch` compatibility, structured output schemas, OAuth security schemes, safety annotations, and Official MCP Registry metadata
180
196
  - v0.3.1: OAuth 2.1 support for Remote MCP; retired reasoning tool removed
181
197
  - v0.3.0: Remote MCP support via Streamable HTTP; per-session API key authentication
182
198
  - v0.2.0: Fallback `.env` support for LibreChat integration
package/build/api.js CHANGED
@@ -4,13 +4,13 @@ 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
+ * @param apiKey Optional request credential (falls back to global API_KEY)
8
8
  * @returns API response
9
9
  */
10
10
  export async function makeRequest(endpoint, data, apiKey) {
11
11
  const key = apiKey || API_KEY;
12
12
  if (!key) {
13
- throw new Error("API key is required. Provide SEARCH1API_KEY or pass apiKey per-session.");
13
+ throw new Error("API key is required. Provide SEARCH1API_KEY or pass apiKey explicitly.");
14
14
  }
15
15
  const startTime = Date.now();
16
16
  const baseUrl = API_CONFIG.BASE_URL.replace(/\/+$/, '');
package/build/config.js CHANGED
@@ -27,7 +27,7 @@ if (!API_KEY) {
27
27
  }
28
28
  // Final check
29
29
  if (!API_KEY) {
30
- log('SEARCH1API_KEY not found. Stdio mode requires it; HTTP mode uses per-session keys.');
30
+ log('SEARCH1API_KEY not found. Stdio mode requires it; HTTP mode uses per-request credentials.');
31
31
  }
32
32
  else {
33
33
  log('API key located successfully.');
package/build/http.js CHANGED
@@ -1,69 +1,19 @@
1
1
  #!/usr/bin/env node
2
- import { createHash, randomUUID } from "node:crypto";
3
- import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
2
+ import { createHash } from "node:crypto";
3
+ import { pathToFileURL } from "node:url";
4
+ import { hostHeaderValidation, toNodeHandler, } from "@modelcontextprotocol/node";
5
+ import { createMcpHandler, } from "@modelcontextprotocol/server";
4
6
  import express from "express";
5
7
  import { createMcpServer } from "./server.js";
6
8
  import { log } from "./utils.js";
7
- const app = express();
8
9
  const API_BASE_URL = process.env.SEARCH1API_API_URL || "https://api.search1api.com";
9
10
  const AUTHORIZATION_SERVER = "https://clerk.search1api.com";
10
11
  const MCP_RESOURCE = "https://mcp.search1api.com/mcp";
11
12
  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) {
13
+ /**
14
+ * Validate both Clerk OAuth tokens and legacy Search1API API keys at the API.
15
+ */
16
+ export async function validateCredential(credential) {
67
17
  const response = await fetch(`${API_BASE_URL}/usage`, {
68
18
  headers: { Authorization: `Bearer ${credential}` },
69
19
  });
@@ -87,7 +37,139 @@ async function validateCredential(credential) {
87
37
  }
88
38
  return { credential, principal };
89
39
  }
90
- async function authenticateMcpRequest(req, res, expectedPrincipal) {
40
+ /**
41
+ * Build the HTTP application without starting a listener.
42
+ *
43
+ * A single v2 handler serves the 2026-07-28 protocol and the SDK's default
44
+ * stateless 2025 fallback. Authentication is validated for every exchange,
45
+ * so no credential or principal is retained in a server-side MCP session.
46
+ */
47
+ export function createHttpApp(options = {}) {
48
+ const app = express();
49
+ const credentialValidator = options.validateCredential ?? validateCredential;
50
+ const allowedHostnames = options.allowedHostnames ?? configuredAllowedHostnames();
51
+ const validateHost = hostHeaderValidation(allowedHostnames);
52
+ const mcpHandler = createMcpHandler(({ authInfo }) => createMcpServer(authInfo?.token), {
53
+ legacy: "stateless",
54
+ onerror: (error) => log("MCP handler error:", error),
55
+ });
56
+ const nodeHandler = toNodeHandler(mcpHandler, {
57
+ onerror: (error) => log("MCP Node adapter error:", error),
58
+ });
59
+ app.use((req, res, next) => {
60
+ if (!validateHost(req, res)) {
61
+ return;
62
+ }
63
+ next();
64
+ });
65
+ // The service root is documentation, not an MCP transport endpoint. Keep
66
+ // query parameters so bookmarked campaign/support links remain attributable.
67
+ app.get("/", (req, res) => {
68
+ const target = new URL("https://www.search1api.com/docs/integrations/mcp");
69
+ for (const [key, value] of Object.entries(req.query)) {
70
+ if (typeof value === "string") {
71
+ target.searchParams.append(key, value);
72
+ }
73
+ }
74
+ res.redirect(301, target.toString());
75
+ });
76
+ const protectedResourceMetadata = {
77
+ resource: MCP_RESOURCE,
78
+ authorization_servers: [AUTHORIZATION_SERVER],
79
+ bearer_methods_supported: ["header"],
80
+ scopes_supported: ["openid", "offline_access"],
81
+ resource_documentation: "https://www.search1api.com/auth.md",
82
+ };
83
+ app.get([
84
+ "/.well-known/oauth-protected-resource",
85
+ "/.well-known/oauth-protected-resource/mcp",
86
+ ], (_req, res) => {
87
+ res.type("application/json").json(protectedResourceMetadata);
88
+ });
89
+ app.get("/.well-known/oauth-authorization-server", (_req, res) => {
90
+ res.redirect(302, `${AUTHORIZATION_SERVER}/.well-known/oauth-authorization-server`);
91
+ });
92
+ app.use(express.json());
93
+ app.all("/mcp", async (req, res) => {
94
+ const authenticated = await authenticateMcpRequest(req, res, credentialValidator);
95
+ if (!authenticated) {
96
+ return;
97
+ }
98
+ const authInfo = {
99
+ token: authenticated.credential,
100
+ clientId: authenticated.principal,
101
+ scopes: [],
102
+ };
103
+ req.auth = authInfo;
104
+ await nodeHandler(req, res, req.body);
105
+ });
106
+ return {
107
+ app,
108
+ mcpHandler,
109
+ close: () => mcpHandler.close(),
110
+ };
111
+ }
112
+ function configuredAllowedHostnames() {
113
+ const configured = (process.env.MCP_ALLOWED_HOSTS ?? "")
114
+ .split(",")
115
+ .map((hostname) => hostname.trim())
116
+ .filter(Boolean);
117
+ return [
118
+ ...new Set([
119
+ "mcp.search1api.com",
120
+ "localhost",
121
+ "127.0.0.1",
122
+ "[::1]",
123
+ ...configured,
124
+ ]),
125
+ ];
126
+ }
127
+ /** Start the production HTTP listener. */
128
+ export function startHttpServer(port = Number.parseInt(process.env.PORT || "3000", 10)) {
129
+ const httpApp = createHttpApp();
130
+ const httpServer = httpApp.app.listen(port, () => {
131
+ log(`Search1API MCP HTTP server listening on http://localhost:${port}/mcp`);
132
+ });
133
+ let closing = false;
134
+ const shutdown = async () => {
135
+ if (closing) {
136
+ return;
137
+ }
138
+ closing = true;
139
+ log("Shutting down HTTP server...");
140
+ await httpApp.close();
141
+ if (httpServer.listening) {
142
+ await new Promise((resolve, reject) => {
143
+ httpServer.close((error) => (error ? reject(error) : resolve()));
144
+ });
145
+ }
146
+ };
147
+ process.once("SIGINT", shutdown);
148
+ process.once("SIGTERM", shutdown);
149
+ return { ...httpApp, httpServer, close: shutdown };
150
+ }
151
+ /** Extract a Bearer credential, retaining the legacy query-key fallback. */
152
+ function extractCredential(req) {
153
+ const auth = req.headers.authorization;
154
+ if (auth?.startsWith("Bearer ")) {
155
+ return auth.slice(7).trim() || undefined;
156
+ }
157
+ const queryKey = req.query.apiKey;
158
+ if (typeof queryKey === "string" && queryKey.trim()) {
159
+ return queryKey.trim();
160
+ }
161
+ return undefined;
162
+ }
163
+ function challenge(res, message, error) {
164
+ const errorParameter = error ? `, error="${error}"` : "";
165
+ res.set("WWW-Authenticate", `Bearer resource_metadata="${MCP_RESOURCE_METADATA}"${errorParameter}`);
166
+ res.status(401).json({
167
+ jsonrpc: "2.0",
168
+ error: { code: -32001, message },
169
+ id: null,
170
+ });
171
+ }
172
+ async function authenticateMcpRequest(req, res, credentialValidator) {
91
173
  const credential = extractCredential(req);
92
174
  if (!credential) {
93
175
  challenge(res, "Authentication is required. Use OAuth 2.1 discovery or provide a Search1API API key as a Bearer token.");
@@ -95,7 +177,7 @@ async function authenticateMcpRequest(req, res, expectedPrincipal) {
95
177
  }
96
178
  let authenticated;
97
179
  try {
98
- authenticated = await validateCredential(credential);
180
+ authenticated = await credentialValidator(credential);
99
181
  }
100
182
  catch (error) {
101
183
  log("Credential validation failed:", error);
@@ -113,127 +195,19 @@ async function authenticateMcpRequest(req, res, expectedPrincipal) {
113
195
  challenge(res, "The Bearer credential is invalid or expired.", "invalid_token");
114
196
  return null;
115
197
  }
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
198
  return authenticated;
128
199
  }
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,
200
+ function installGlobalErrorLogging() {
201
+ process.on("uncaughtException", (error) => {
202
+ log("Uncaught exception:", error);
188
203
  });
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,
204
+ process.on("unhandledRejection", (reason) => {
205
+ log("Unhandled rejection:", reason);
228
206
  });
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
- });
207
+ }
208
+ const isMain = process.argv[1] !== undefined &&
209
+ import.meta.url === pathToFileURL(process.argv[1]).href;
210
+ if (isMain) {
211
+ installGlobalErrorLogging();
212
+ startHttpServer();
213
+ }
package/build/index.js CHANGED
@@ -1,48 +1,44 @@
1
1
  #!/usr/bin/env node
2
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
- import { log } from "./utils.js";
4
- import { createMcpServer } from "./server.js";
2
+ import { serveStdio } from "@modelcontextprotocol/server/stdio";
5
3
  import { API_KEY } from "./config.js";
6
- /**
7
- * Main function - Program entry point (stdio mode)
8
- */
9
- async function main() {
10
- // Stdio mode requires API key at startup
4
+ import { createMcpServer } from "./server.js";
5
+ import { log } from "./utils.js";
6
+ function main() {
11
7
  if (!API_KEY) {
12
8
  log("SEARCH1API_KEY environment variable is not set");
13
9
  process.exit(1);
14
10
  }
15
- try {
16
- log("Starting Search1API MCP server (stdio mode)");
17
- const server = createMcpServer();
18
- const transport = new StdioServerTransport();
19
- await server.connect(transport);
20
- log("Server started successfully");
21
- // Handle process exit signals
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);
31
- }
32
- catch (error) {
33
- log("Failed to start server:", error);
34
- process.exit(1);
35
- }
11
+ log("Starting Search1API MCP server (stdio mode)");
12
+ const handle = serveStdio(() => createMcpServer(API_KEY), {
13
+ legacy: "serve",
14
+ onerror: (error) => log("MCP stdio error:", error),
15
+ });
16
+ log("Server started successfully");
17
+ let closing = false;
18
+ const exitHandler = async () => {
19
+ if (closing) {
20
+ return;
21
+ }
22
+ closing = true;
23
+ log("Shutting down server...");
24
+ await handle.close();
25
+ process.exit(0);
26
+ };
27
+ process.once("SIGINT", exitHandler);
28
+ process.once("SIGTERM", exitHandler);
29
+ process.once("SIGUSR1", exitHandler);
30
+ process.once("SIGUSR2", exitHandler);
36
31
  }
37
- // Handle global errors
38
32
  process.on("uncaughtException", (error) => {
39
33
  log("Uncaught exception:", error);
40
34
  });
41
35
  process.on("unhandledRejection", (reason) => {
42
36
  log("Unhandled rejection:", reason);
43
37
  });
44
- // Start program
45
- main().catch((error) => {
46
- log("Fatal error:", error);
38
+ try {
39
+ main();
40
+ }
41
+ catch (error) {
42
+ log("Failed to start server:", error);
47
43
  process.exit(1);
48
- });
44
+ }
@@ -1,5 +1,5 @@
1
- import { McpError, ErrorCode } from "@modelcontextprotocol/sdk/types.js";
2
- import { log } from './utils.js';
1
+ import { ResourceNotFoundError } from "@modelcontextprotocol/server";
2
+ import { log } from "./utils.js";
3
3
  /**
4
4
  * Define the default search query result resource
5
5
  */
@@ -28,7 +28,7 @@ export function handleReadResource(resourceUri) {
28
28
  log(`Handling read resource request for ${resourceUri}`);
29
29
  const resource = RESOURCES.find((r) => r.uri === resourceUri);
30
30
  if (!resource) {
31
- throw new McpError(ErrorCode.InvalidRequest, `Resource not found: ${resourceUri}`);
31
+ throw new ResourceNotFoundError(resourceUri);
32
32
  }
33
33
  return resource;
34
34
  }