search1api-mcp 0.4.0 → 0.5.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
@@ -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,12 +125,17 @@ 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. Results use the standard citable
132
- `id`/`title`/`url` shape expected by ChatGPT deep research and company
133
- knowledge.
136
+ Search the web using Search1API. Results include a citable
137
+ `id`/`title`/`url` structure. Pass a result URL to `crawl` when you need the
138
+ full page.
134
139
 
135
140
  | Parameter | Required | Default | Description |
136
141
  |-----------|----------|---------|-------------|
@@ -142,13 +147,6 @@ knowledge.
142
147
  | `exclude_sites` | No | [] | Sites to exclude |
143
148
  | `time_range` | No | - | day, month, year |
144
149
 
145
- ### fetch
146
- Retrieve the full readable contents of a result returned by `search`.
147
-
148
- | Parameter | Required | Description |
149
- |-----------|----------|-------------|
150
- | `id` | Yes | Result ID returned by `search` (the canonical page URL) |
151
-
152
150
  ### news
153
151
  Search for news articles.
154
152
 
@@ -186,7 +184,9 @@ Get trending topics from popular platforms.
186
184
 
187
185
  ## Version History
188
186
 
189
- - v0.4.0: Standard `search`/`fetch` compatibility, structured output schemas, OAuth security schemes, safety annotations, and Official MCP Registry metadata
187
+ - v0.5.1: Duplicate `fetch` tool removed; pass search result URLs directly to `crawl`
188
+ - v0.5.0: MCP 2026-07-28 support with automatic protocol negotiation; stateless compatibility for 2025-era HTTP clients; request-level authentication
189
+ - v0.4.0: Initial `search`/`fetch` compatibility, structured output schemas, OAuth security schemes, safety annotations, and Official MCP Registry metadata
190
190
  - v0.3.1: OAuth 2.1 support for Remote MCP; retired reasoning tool removed
191
191
  - v0.3.0: Remote MCP support via Streamable HTTP; per-session API key authentication
192
192
  - 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,147 @@ 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
+ // /mcp is a transport endpoint that answers unauthenticated crawlers with
77
+ // 401, so search engines gain nothing from walking this host. Keep the OAuth
78
+ // discovery documents reachable for agents.
79
+ app.get("/robots.txt", (_req, res) => {
80
+ res
81
+ .type("text/plain")
82
+ .send(["User-agent: *", "Disallow: /", "Allow: /.well-known/", ""].join("\n"));
83
+ });
84
+ const protectedResourceMetadata = {
85
+ resource: MCP_RESOURCE,
86
+ authorization_servers: [AUTHORIZATION_SERVER],
87
+ bearer_methods_supported: ["header"],
88
+ scopes_supported: ["openid", "offline_access"],
89
+ resource_documentation: "https://www.search1api.com/auth.md",
90
+ };
91
+ app.get([
92
+ "/.well-known/oauth-protected-resource",
93
+ "/.well-known/oauth-protected-resource/mcp",
94
+ ], (_req, res) => {
95
+ res.type("application/json").json(protectedResourceMetadata);
96
+ });
97
+ app.get("/.well-known/oauth-authorization-server", (_req, res) => {
98
+ res.redirect(302, `${AUTHORIZATION_SERVER}/.well-known/oauth-authorization-server`);
99
+ });
100
+ app.use(express.json());
101
+ app.all("/mcp", async (req, res) => {
102
+ const authenticated = await authenticateMcpRequest(req, res, credentialValidator);
103
+ if (!authenticated) {
104
+ return;
105
+ }
106
+ const authInfo = {
107
+ token: authenticated.credential,
108
+ clientId: authenticated.principal,
109
+ scopes: [],
110
+ };
111
+ req.auth = authInfo;
112
+ await nodeHandler(req, res, req.body);
113
+ });
114
+ return {
115
+ app,
116
+ mcpHandler,
117
+ close: () => mcpHandler.close(),
118
+ };
119
+ }
120
+ function configuredAllowedHostnames() {
121
+ const configured = (process.env.MCP_ALLOWED_HOSTS ?? "")
122
+ .split(",")
123
+ .map((hostname) => hostname.trim())
124
+ .filter(Boolean);
125
+ return [
126
+ ...new Set([
127
+ "mcp.search1api.com",
128
+ "localhost",
129
+ "127.0.0.1",
130
+ "[::1]",
131
+ ...configured,
132
+ ]),
133
+ ];
134
+ }
135
+ /** Start the production HTTP listener. */
136
+ export function startHttpServer(port = Number.parseInt(process.env.PORT || "3000", 10)) {
137
+ const httpApp = createHttpApp();
138
+ const httpServer = httpApp.app.listen(port, () => {
139
+ log(`Search1API MCP HTTP server listening on http://localhost:${port}/mcp`);
140
+ });
141
+ let closing = false;
142
+ const shutdown = async () => {
143
+ if (closing) {
144
+ return;
145
+ }
146
+ closing = true;
147
+ log("Shutting down HTTP server...");
148
+ await httpApp.close();
149
+ if (httpServer.listening) {
150
+ await new Promise((resolve, reject) => {
151
+ httpServer.close((error) => (error ? reject(error) : resolve()));
152
+ });
153
+ }
154
+ };
155
+ process.once("SIGINT", shutdown);
156
+ process.once("SIGTERM", shutdown);
157
+ return { ...httpApp, httpServer, close: shutdown };
158
+ }
159
+ /** Extract a Bearer credential, retaining the legacy query-key fallback. */
160
+ function extractCredential(req) {
161
+ const auth = req.headers.authorization;
162
+ if (auth?.startsWith("Bearer ")) {
163
+ return auth.slice(7).trim() || undefined;
164
+ }
165
+ const queryKey = req.query.apiKey;
166
+ if (typeof queryKey === "string" && queryKey.trim()) {
167
+ return queryKey.trim();
168
+ }
169
+ return undefined;
170
+ }
171
+ function challenge(res, message, error) {
172
+ const errorParameter = error ? `, error="${error}"` : "";
173
+ res.set("WWW-Authenticate", `Bearer resource_metadata="${MCP_RESOURCE_METADATA}"${errorParameter}`);
174
+ res.status(401).json({
175
+ jsonrpc: "2.0",
176
+ error: { code: -32001, message },
177
+ id: null,
178
+ });
179
+ }
180
+ async function authenticateMcpRequest(req, res, credentialValidator) {
91
181
  const credential = extractCredential(req);
92
182
  if (!credential) {
93
183
  challenge(res, "Authentication is required. Use OAuth 2.1 discovery or provide a Search1API API key as a Bearer token.");
@@ -95,7 +185,7 @@ async function authenticateMcpRequest(req, res, expectedPrincipal) {
95
185
  }
96
186
  let authenticated;
97
187
  try {
98
- authenticated = await validateCredential(credential);
188
+ authenticated = await credentialValidator(credential);
99
189
  }
100
190
  catch (error) {
101
191
  log("Credential validation failed:", error);
@@ -113,127 +203,19 @@ async function authenticateMcpRequest(req, res, expectedPrincipal) {
113
203
  challenge(res, "The Bearer credential is invalid or expired.", "invalid_token");
114
204
  return null;
115
205
  }
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
206
  return authenticated;
128
207
  }
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,
208
+ function installGlobalErrorLogging() {
209
+ process.on("uncaughtException", (error) => {
210
+ log("Uncaught exception:", error);
188
211
  });
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,
212
+ process.on("unhandledRejection", (reason) => {
213
+ log("Unhandled rejection:", reason);
228
214
  });
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
- });
215
+ }
216
+ const isMain = process.argv[1] !== undefined &&
217
+ import.meta.url === pathToFileURL(process.argv[1]).href;
218
+ if (isMain) {
219
+ installGlobalErrorLogging();
220
+ startHttpServer();
221
+ }
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
  }
package/build/server.js CHANGED
@@ -1,86 +1,72 @@
1
- import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
- import { McpError, ErrorCode, CallToolRequestSchema, ListResourcesRequestSchema, ReadResourceRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
1
+ import { INTERNAL_ERROR, McpServer, ProtocolError, fromJsonSchema, } from "@modelcontextprotocol/server";
2
+ import { handleReadResource, RESOURCES } from "./resources.js";
3
3
  import { handleToolCall } from "./tools/handlers.js";
4
- import { log, formatError } from "./utils.js";
5
- import { handleListResources, handleReadResource } from "./resources.js";
6
4
  import { ALL_TOOLS } from "./tools/index.js";
5
+ import { formatError, log } from "./utils.js";
7
6
  import { PACKAGE_VERSION } from "./version.js";
8
7
  /**
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
8
+ * Create one transport-neutral MCP server instance.
9
+ *
10
+ * The v2 serving entries call this factory once per modern HTTP exchange,
11
+ * once per stateless legacy HTTP request, or once per stdio connection.
14
12
  */
15
13
  export function createMcpServer(credential) {
16
14
  log("Creating Search1API MCP server");
17
- const server = new Server({
15
+ const server = new McpServer({
18
16
  name: "search1api-server",
19
- version: PACKAGE_VERSION
20
- }, {
21
- capabilities: {
22
- resources: {},
23
- tools: {}
24
- }
17
+ version: PACKAGE_VERSION,
25
18
  });
26
- setupRequestHandlers(server, credential);
19
+ for (const tool of ALL_TOOLS) {
20
+ const inputSchema = fromJsonSchema(tool.inputSchema);
21
+ const outputSchema = tool.outputSchema
22
+ ? fromJsonSchema(tool.outputSchema)
23
+ : undefined;
24
+ server.registerTool(tool.name, {
25
+ title: tool.title,
26
+ description: tool.description,
27
+ inputSchema,
28
+ ...(outputSchema ? { outputSchema } : {}),
29
+ annotations: tool.annotations,
30
+ _meta: tool._meta,
31
+ }, async (args) => {
32
+ try {
33
+ const bearerCredential = typeof credential === "function" ? credential() : credential;
34
+ log(`Tool call received: ${tool.name}`);
35
+ return await handleToolCall(tool.name, args, bearerCredential);
36
+ }
37
+ catch (error) {
38
+ throw normalizeProtocolError(`handling tool call ${tool.name}`, error);
39
+ }
40
+ });
41
+ }
42
+ for (const resource of RESOURCES) {
43
+ server.registerResource(resource.name, resource.uri, {
44
+ description: resource.description,
45
+ mimeType: resource.mimeType,
46
+ }, async (uri) => {
47
+ try {
48
+ const result = handleReadResource(uri.href);
49
+ return {
50
+ contents: [
51
+ {
52
+ uri: uri.href,
53
+ mimeType: result.mimeType || "application/json",
54
+ text: JSON.stringify(result),
55
+ },
56
+ ],
57
+ };
58
+ }
59
+ catch (error) {
60
+ throw normalizeProtocolError("reading resource", error);
61
+ }
62
+ });
63
+ }
27
64
  return server;
28
65
  }
29
- /**
30
- * Helper function to handle errors uniformly
31
- */
32
- function handleError(context, error) {
66
+ function normalizeProtocolError(context, error) {
33
67
  log(`Error ${context}:`, error);
34
- if (error instanceof McpError) {
35
- throw error;
68
+ if (error instanceof ProtocolError) {
69
+ return error;
36
70
  }
37
- throw new McpError(ErrorCode.InternalError, `${context}: ${formatError(error)}`);
38
- }
39
- /**
40
- * Set up server request handlers
41
- */
42
- function setupRequestHandlers(server, credential) {
43
- // Handle tool calls
44
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
45
- try {
46
- const toolName = request.params.name;
47
- const toolArgs = request.params.arguments;
48
- log(`Tool call received: ${toolName}`);
49
- const bearerCredential = typeof credential === "function" ? credential() : credential;
50
- return await handleToolCall(toolName, toolArgs, bearerCredential);
51
- }
52
- catch (error) {
53
- handleError("handling tool call", error);
54
- }
55
- });
56
- // Handle resource listing
57
- server.setRequestHandler(ListResourcesRequestSchema, async () => {
58
- try {
59
- return { resources: handleListResources() };
60
- }
61
- catch (error) {
62
- handleError("listing resources", error);
63
- }
64
- });
65
- // Handle resource reading
66
- server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
67
- try {
68
- const resourceUri = request.params.uri;
69
- const resource = handleReadResource(resourceUri);
70
- return {
71
- contents: [{
72
- uri: resourceUri,
73
- mimeType: resource.mimeType || "application/json",
74
- text: JSON.stringify(resource)
75
- }]
76
- };
77
- }
78
- catch (error) {
79
- handleError("reading resource", error);
80
- }
81
- });
82
- // Handle tool listing
83
- server.setRequestHandler(ListToolsRequestSchema, async () => {
84
- return { tools: ALL_TOOLS };
85
- });
71
+ return new ProtocolError(INTERNAL_ERROR, `${context}: ${formatError(error)}`);
86
72
  }
@@ -2,13 +2,13 @@ import { isValidCrawlArgs } from '../types.js';
2
2
  import { makeRequest } from '../api.js';
3
3
  import { formatError, log } from '../utils.js';
4
4
  import { API_CONFIG } from '../config.js';
5
- import { McpError, ErrorCode } from "@modelcontextprotocol/sdk/types.js";
5
+ import { INVALID_PARAMS, ProtocolError, } from "@modelcontextprotocol/server";
6
6
  /**
7
7
  * Implementation of the crawl tool
8
8
  */
9
9
  export async function handleCrawl(args, apiKey) {
10
10
  if (!isValidCrawlArgs(args)) {
11
- throw new McpError(ErrorCode.InvalidParams, "Invalid crawl arguments");
11
+ throw new ProtocolError(INVALID_PARAMS, "Invalid crawl arguments");
12
12
  }
13
13
  const { url } = args;
14
14
  log("Starting crawl for:", url);
@@ -31,7 +31,6 @@ export async function handleCrawl(args, apiKey) {
31
31
  structuredContent,
32
32
  content: [{
33
33
  type: "text",
34
- mimeType: "application/json",
35
34
  text: JSON.stringify(structuredContent)
36
35
  }]
37
36
  };
@@ -41,7 +40,6 @@ export async function handleCrawl(args, apiKey) {
41
40
  return {
42
41
  content: [{
43
42
  type: "text",
44
- mimeType: "text/plain",
45
43
  text: `Crawl API error: ${formatError(error)}`
46
44
  }],
47
45
  isError: true
@@ -1,17 +1,16 @@
1
- import { McpError, ErrorCode } from "@modelcontextprotocol/sdk/types.js";
2
- import { log } from '../utils.js';
3
- import { handleSearch } from './search.js';
4
- import { handleFetch } from './fetch.js';
5
- import { handleCrawl } from './crawl.js';
6
- import { handleSitemap } from './sitemap.js';
7
- import { handleNews } from './news.js';
8
- import { handleTrending } from './trending.js';
9
- import { SEARCH_TOOL, FETCH_TOOL, CRAWL_TOOL, SITEMAP_TOOL, NEWS_TOOL, TRENDING_TOOL } from './index.js';
1
+ import { INVALID_PARAMS, ProtocolError, } from "@modelcontextprotocol/server";
2
+ import { log } from "../utils.js";
3
+ import { handleSearch } from "./search.js";
4
+ import { handleCrawl } from "./crawl.js";
5
+ import { handleSitemap } from "./sitemap.js";
6
+ import { handleNews } from "./news.js";
7
+ import { handleTrending } from "./trending.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
14
- * @param apiKey Optional per-session API key
13
+ * @param apiKey Optional request credential
15
14
  * @returns Tool processing result
16
15
  */
17
16
  export async function handleToolCall(toolName, args, apiKey) {
@@ -19,8 +18,6 @@ export async function handleToolCall(toolName, args, apiKey) {
19
18
  switch (toolName) {
20
19
  case SEARCH_TOOL.name:
21
20
  return await handleSearch(args, apiKey);
22
- case FETCH_TOOL.name:
23
- return await handleFetch(args, apiKey);
24
21
  case CRAWL_TOOL.name:
25
22
  return await handleCrawl(args, apiKey);
26
23
  case SITEMAP_TOOL.name:
@@ -31,6 +28,6 @@ export async function handleToolCall(toolName, args, apiKey) {
31
28
  return await handleTrending(args, apiKey);
32
29
  default:
33
30
  log(`Unknown tool: ${toolName}`);
34
- throw new McpError(ErrorCode.InvalidParams, `Unknown tool: ${toolName}`);
31
+ throw new ProtocolError(INVALID_PARAMS, `Unknown tool: ${toolName}`);
35
32
  }
36
33
  }
@@ -57,25 +57,11 @@ const SEARCH_OUTPUT_SCHEMA = {
57
57
  },
58
58
  required: ["results"],
59
59
  };
60
- const FETCH_OUTPUT_SCHEMA = {
61
- type: "object",
62
- properties: {
63
- id: { type: "string" },
64
- title: { type: "string" },
65
- text: { type: "string" },
66
- url: { type: "string", format: "uri" },
67
- metadata: {
68
- type: "object",
69
- additionalProperties: true,
70
- },
71
- },
72
- required: ["id", "title", "text", "url"],
73
- };
74
60
  // Search tool definition
75
61
  export const SEARCH_TOOL = {
76
62
  name: "search",
77
63
  title: "Search the web",
78
- description: "Search the live public web when the user needs current information, sources, or research. Returns citable results with id, title, URL, and text. Pass a result id to fetch to retrieve the full page.",
64
+ description: "Search the live public web when the user needs current information, sources, or research. Returns citable results with id, title, URL, and text. Pass a result URL to crawl to retrieve the full page.",
79
65
  ...AUTHENTICATED_READ_ONLY_WEB,
80
66
  inputSchema: {
81
67
  type: "object",
@@ -129,24 +115,6 @@ export const SEARCH_TOOL = {
129
115
  },
130
116
  outputSchema: SEARCH_OUTPUT_SCHEMA,
131
117
  };
132
- // Fetch tool definition for ChatGPT deep research and company knowledge.
133
- export const FETCH_TOOL = {
134
- name: "fetch",
135
- title: "Fetch a search result",
136
- description: "Retrieve the full readable contents of a result returned by search. Pass the result id, which is the canonical page URL. Returns id, title, full text, URL, and metadata.",
137
- ...AUTHENTICATED_READ_ONLY_WEB,
138
- inputSchema: {
139
- type: "object",
140
- properties: {
141
- id: {
142
- type: "string",
143
- description: "Result id returned by search; for web results this is the canonical URL",
144
- },
145
- },
146
- required: ["id"],
147
- },
148
- outputSchema: FETCH_OUTPUT_SCHEMA,
149
- };
150
118
  // News tool definition
151
119
  export const NEWS_TOOL = {
152
120
  name: "news",
@@ -209,7 +177,7 @@ export const NEWS_TOOL = {
209
177
  export const CRAWL_TOOL = {
210
178
  name: "crawl",
211
179
  title: "Read a web page",
212
- description: "Extract the readable title and full text from a specific public URL supplied by the user. Use fetch instead when following a result returned by search.",
180
+ description: "Extract the readable title and full text from a public URL supplied by the user or returned by search.",
213
181
  ...AUTHENTICATED_READ_ONLY_WEB,
214
182
  inputSchema: {
215
183
  type: "object",
@@ -307,7 +275,6 @@ export const TRENDING_TOOL = {
307
275
  };
308
276
  export const ALL_TOOLS = [
309
277
  SEARCH_TOOL,
310
- FETCH_TOOL,
311
278
  NEWS_TOOL,
312
279
  CRAWL_TOOL,
313
280
  SITEMAP_TOOL,
@@ -2,13 +2,13 @@ import { isValidNewsArgs } from '../types.js';
2
2
  import { makeRequest } from '../api.js';
3
3
  import { formatError, log } from '../utils.js';
4
4
  import { API_CONFIG } from '../config.js';
5
- import { McpError, ErrorCode } from "@modelcontextprotocol/sdk/types.js";
5
+ import { INVALID_PARAMS, ProtocolError, } from "@modelcontextprotocol/server";
6
6
  /**
7
7
  * Implementation of the news search tool
8
8
  */
9
9
  export async function handleNews(args, apiKey) {
10
10
  if (!isValidNewsArgs(args)) {
11
- throw new McpError(ErrorCode.InvalidParams, "Invalid news search arguments");
11
+ throw new ProtocolError(INVALID_PARAMS, "Invalid news search arguments");
12
12
  }
13
13
  log("Processing news search with query:", args.query);
14
14
  try {
@@ -28,7 +28,6 @@ export async function handleNews(args, apiKey) {
28
28
  structuredContent,
29
29
  content: [{
30
30
  type: "text",
31
- mimeType: "application/json",
32
31
  text: JSON.stringify(structuredContent)
33
32
  }]
34
33
  };
@@ -38,7 +37,6 @@ export async function handleNews(args, apiKey) {
38
37
  return {
39
38
  content: [{
40
39
  type: "text",
41
- mimeType: "text/plain",
42
40
  text: `News API error: ${formatError(error)}`
43
41
  }],
44
42
  isError: true
@@ -2,13 +2,13 @@ import { isValidSearchArgs } from '../types.js';
2
2
  import { makeRequest } from '../api.js';
3
3
  import { formatError } from '../utils.js';
4
4
  import { API_CONFIG } from '../config.js';
5
- import { McpError, ErrorCode } from "@modelcontextprotocol/sdk/types.js";
5
+ import { INVALID_PARAMS, ProtocolError, } from "@modelcontextprotocol/server";
6
6
  /**
7
7
  * Implementation of the search tool
8
8
  */
9
9
  export async function handleSearch(args, apiKey) {
10
10
  if (!isValidSearchArgs(args)) {
11
- throw new McpError(ErrorCode.InvalidParams, "Invalid search arguments");
11
+ throw new ProtocolError(INVALID_PARAMS, "Invalid search arguments");
12
12
  }
13
13
  try {
14
14
  const response = await makeRequest(API_CONFIG.ENDPOINTS.SEARCH, args, apiKey);
@@ -27,7 +27,6 @@ export async function handleSearch(args, apiKey) {
27
27
  structuredContent,
28
28
  content: [{
29
29
  type: "text",
30
- mimeType: "application/json",
31
30
  text: JSON.stringify(structuredContent)
32
31
  }]
33
32
  };
@@ -36,7 +35,6 @@ export async function handleSearch(args, apiKey) {
36
35
  return {
37
36
  content: [{
38
37
  type: "text",
39
- mimeType: "text/plain",
40
38
  text: `Search API error: ${formatError(error)}`
41
39
  }],
42
40
  isError: true
@@ -2,13 +2,13 @@ import { isValidSitemapArgs } from '../types.js';
2
2
  import { makeRequest } from '../api.js';
3
3
  import { formatError } from '../utils.js';
4
4
  import { API_CONFIG } from '../config.js';
5
- import { McpError, ErrorCode } from "@modelcontextprotocol/sdk/types.js";
5
+ import { INVALID_PARAMS, ProtocolError, } from "@modelcontextprotocol/server";
6
6
  /**
7
7
  * Implementation of the sitemap tool
8
8
  */
9
9
  export async function handleSitemap(args, apiKey) {
10
10
  if (!isValidSitemapArgs(args)) {
11
- throw new McpError(ErrorCode.InvalidParams, "Invalid sitemap arguments");
11
+ throw new ProtocolError(INVALID_PARAMS, "Invalid sitemap arguments");
12
12
  }
13
13
  try {
14
14
  const response = await makeRequest(API_CONFIG.ENDPOINTS.SITEMAP, args, apiKey);
@@ -17,7 +17,6 @@ export async function handleSitemap(args, apiKey) {
17
17
  structuredContent,
18
18
  content: [{
19
19
  type: "text",
20
- mimeType: "application/json",
21
20
  text: JSON.stringify(structuredContent)
22
21
  }]
23
22
  };
@@ -26,7 +25,6 @@ export async function handleSitemap(args, apiKey) {
26
25
  return {
27
26
  content: [{
28
27
  type: "text",
29
- mimeType: "text/plain",
30
28
  text: `Sitemap API error: ${formatError(error)}`
31
29
  }],
32
30
  isError: true
@@ -2,13 +2,13 @@ import { isValidTrendingArgs } from '../types.js';
2
2
  import { makeRequest } from '../api.js';
3
3
  import { formatError } from '../utils.js';
4
4
  import { API_CONFIG } from '../config.js';
5
- import { McpError, ErrorCode } from "@modelcontextprotocol/sdk/types.js";
5
+ import { INVALID_PARAMS, ProtocolError, } from "@modelcontextprotocol/server";
6
6
  /**
7
7
  * Implementation of the trending tool
8
8
  */
9
9
  export async function handleTrending(args, apiKey) {
10
10
  if (!isValidTrendingArgs(args)) {
11
- throw new McpError(ErrorCode.InvalidParams, "Invalid trending arguments");
11
+ throw new ProtocolError(INVALID_PARAMS, "Invalid trending arguments");
12
12
  }
13
13
  try {
14
14
  const response = await makeRequest(API_CONFIG.ENDPOINTS.TRENDING, args, apiKey);
@@ -17,7 +17,6 @@ export async function handleTrending(args, apiKey) {
17
17
  structuredContent,
18
18
  content: [{
19
19
  type: "text",
20
- mimeType: "application/json",
21
20
  text: JSON.stringify(structuredContent)
22
21
  }]
23
22
  };
@@ -26,7 +25,6 @@ export async function handleTrending(args, apiKey) {
26
25
  return {
27
26
  content: [{
28
27
  type: "text",
29
- mimeType: "text/plain",
30
28
  text: `Trending API error: ${formatError(error)}`
31
29
  }],
32
30
  isError: true
package/build/types.js CHANGED
@@ -62,13 +62,6 @@ export function isValidSearchArgs(args) {
62
62
  }
63
63
  return true;
64
64
  }
65
- export function isValidFetchArgs(args) {
66
- if (typeof args !== "object" || args === null) {
67
- return false;
68
- }
69
- const { id } = args;
70
- return typeof id === "string" && id.trim().length > 0;
71
- }
72
65
  export function isValidCrawlArgs(args) {
73
66
  if (typeof args !== 'object' || args === null) {
74
67
  return false;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "search1api-mcp",
3
- "version": "0.4.0",
3
+ "version": "0.5.1",
4
4
  "mcpName": "io.github.superagents-lab/search1api",
5
5
  "description": "A Model Context Protocol (MCP) server that provides search and crawl functionality using Search1API",
6
6
  "private": false,
@@ -23,11 +23,13 @@
23
23
  "sync:manifest": "npm run build && node scripts/sync-lobe-manifest.mjs"
24
24
  },
25
25
  "dependencies": {
26
- "@modelcontextprotocol/sdk": "^1.29.0",
26
+ "@modelcontextprotocol/node": "^2.0.0",
27
+ "@modelcontextprotocol/server": "^2.0.0",
27
28
  "dotenv": "^16.6.1",
28
29
  "express": "^4.22.2"
29
30
  },
30
31
  "devDependencies": {
32
+ "@modelcontextprotocol/client": "^2.0.0",
31
33
  "@types/express": "^5.0.6",
32
34
  "@types/node": "^20.19.43",
33
35
  "typescript": "^5.9.3"
@@ -54,6 +56,6 @@
54
56
  "access": "public"
55
57
  },
56
58
  "engines": {
57
- "node": ">=18.0.0"
59
+ "node": ">=20.0.0"
58
60
  }
59
61
  }
package/server.json CHANGED
@@ -7,7 +7,7 @@
7
7
  "url": "https://github.com/superagents-lab/search1api-mcp",
8
8
  "source": "github"
9
9
  },
10
- "version": "0.4.0",
10
+ "version": "0.5.1",
11
11
  "remotes": [
12
12
  {
13
13
  "type": "streamable-http",
@@ -18,7 +18,7 @@
18
18
  {
19
19
  "registryType": "npm",
20
20
  "identifier": "search1api-mcp",
21
- "version": "0.4.0",
21
+ "version": "0.5.1",
22
22
  "transport": {
23
23
  "type": "stdio"
24
24
  },
@@ -1,51 +0,0 @@
1
- import { ErrorCode, McpError } from "@modelcontextprotocol/sdk/types.js";
2
- import { makeRequest } from "../api.js";
3
- import { API_CONFIG } from "../config.js";
4
- import { isValidFetchArgs, } from "../types.js";
5
- import { formatError, log } from "../utils.js";
6
- /**
7
- * ChatGPT-compatible fetch implementation. Search result IDs are canonical
8
- * URLs, so fetch can pass the ID directly to the crawl endpoint.
9
- */
10
- export async function handleFetch(args, apiKey) {
11
- if (!isValidFetchArgs(args)) {
12
- throw new McpError(ErrorCode.InvalidParams, "Invalid fetch arguments");
13
- }
14
- const { id } = args;
15
- log("Fetching search result:", id);
16
- try {
17
- const response = await makeRequest(API_CONFIG.ENDPOINTS.CRAWL, { url: id }, apiKey);
18
- const result = {
19
- id,
20
- title: response.results.title,
21
- text: response.results.content,
22
- url: response.results.link || id,
23
- metadata: {
24
- source: "search1api",
25
- },
26
- };
27
- return {
28
- structuredContent: result,
29
- content: [
30
- {
31
- type: "text",
32
- mimeType: "application/json",
33
- text: JSON.stringify(result),
34
- },
35
- ],
36
- };
37
- }
38
- catch (error) {
39
- log("Fetch error:", error);
40
- return {
41
- content: [
42
- {
43
- type: "text",
44
- mimeType: "text/plain",
45
- text: `Fetch API error: ${formatError(error)}`,
46
- },
47
- ],
48
- isError: true,
49
- };
50
- }
51
- }