search1api-mcp 0.4.0 → 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
@@ -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,6 +125,11 @@ 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
@@ -186,6 +191,7 @@ Get trending topics from popular platforms.
186
191
 
187
192
  ## Version History
188
193
 
194
+ - v0.5.0: MCP 2026-07-28 support with automatic protocol negotiation; stateless compatibility for 2025-era HTTP clients; request-level authentication
189
195
  - v0.4.0: Standard `search`/`fetch` compatibility, structured output schemas, OAuth security schemes, safety annotations, and Official MCP Registry metadata
190
196
  - v0.3.1: OAuth 2.1 support for Remote MCP; retired reasoning tool removed
191
197
  - v0.3.0: Remote MCP support via Streamable HTTP; per-session API key authentication
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
  }
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,4 +1,4 @@
1
- import { ErrorCode, McpError } from "@modelcontextprotocol/sdk/types.js";
1
+ import { INVALID_PARAMS, ProtocolError, } from "@modelcontextprotocol/server";
2
2
  import { makeRequest } from "../api.js";
3
3
  import { API_CONFIG } from "../config.js";
4
4
  import { isValidFetchArgs, } from "../types.js";
@@ -9,7 +9,7 @@ import { formatError, log } from "../utils.js";
9
9
  */
10
10
  export async function handleFetch(args, apiKey) {
11
11
  if (!isValidFetchArgs(args)) {
12
- throw new McpError(ErrorCode.InvalidParams, "Invalid fetch arguments");
12
+ throw new ProtocolError(INVALID_PARAMS, "Invalid fetch arguments");
13
13
  }
14
14
  const { id } = args;
15
15
  log("Fetching search result:", id);
@@ -29,7 +29,6 @@ export async function handleFetch(args, apiKey) {
29
29
  content: [
30
30
  {
31
31
  type: "text",
32
- mimeType: "application/json",
33
32
  text: JSON.stringify(result),
34
33
  },
35
34
  ],
@@ -41,7 +40,6 @@ export async function handleFetch(args, apiKey) {
41
40
  content: [
42
41
  {
43
42
  type: "text",
44
- mimeType: "text/plain",
45
43
  text: `Fetch API error: ${formatError(error)}`,
46
44
  },
47
45
  ],
@@ -1,17 +1,17 @@
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 { 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";
10
10
  /**
11
11
  * Dispatch request based on tool name
12
12
  * @param toolName Name of the tool
13
13
  * @param args Tool parameters
14
- * @param apiKey Optional per-session API key
14
+ * @param apiKey Optional request credential
15
15
  * @returns Tool processing result
16
16
  */
17
17
  export async function handleToolCall(toolName, args, apiKey) {
@@ -31,6 +31,6 @@ export async function handleToolCall(toolName, args, apiKey) {
31
31
  return await handleTrending(args, apiKey);
32
32
  default:
33
33
  log(`Unknown tool: ${toolName}`);
34
- throw new McpError(ErrorCode.InvalidParams, `Unknown tool: ${toolName}`);
34
+ throw new ProtocolError(INVALID_PARAMS, `Unknown tool: ${toolName}`);
35
35
  }
36
36
  }
@@ -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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "search1api-mcp",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
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.0",
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.0",
22
22
  "transport": {
23
23
  "type": "stdio"
24
24
  },