search1api-mcp 0.5.4 → 0.6.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
@@ -11,6 +11,7 @@ The official MCP server for [Search1API](https://s1.dev/?utm_source=mcp) — web
11
11
 
12
12
  - OAuth-aware clients can connect to the Remote MCP URL directly, then sign in and approve access in the browser.
13
13
  - Existing integrations can continue to use an API key from the [Search1API dashboard](https://dashboard.search1api.com).
14
+ - Tool calls always require a credential. Tool discovery (`initialize`, `tools/list`) is answered without one, so clients and directories can inspect the server before signing in.
14
15
 
15
16
  ## Quick Start (Remote MCP)
16
17
 
@@ -196,6 +197,8 @@ Get trending topics from popular platforms.
196
197
 
197
198
  ## Version History
198
199
 
200
+ - v0.6.0: MCP discovery (`initialize`, `tools/list`, `resources/*`, `prompts/list`, `server/discover`) is served without a credential so clients and directories can enumerate tools before signing in; tool calls still require OAuth or an API key. Stdio mode starts without `SEARCH1API_KEY` and serves tool metadata, refusing only at call time. Malformed requests answer as JSON-RPC instead of an HTML error page
201
+ - v0.5.4: OAuth issuer moved to `clerk.s1.dev` and is configurable with `OAUTH_AUTHORIZATION_SERVER`; MCP server card published at `/.well-known/mcp/server-card.json`; OAuth discovery documents now send cache headers
199
202
  - v0.5.3: OAuth resource and tool metadata no longer require OIDC session scopes; Smithery and Glama registry badges added
200
203
  - v0.5.2: MCP `Origin` validation now runs before request parsing and authentication; self-hosted HTTP deployments can configure trusted browser origins with `MCP_ALLOWED_ORIGINS`
201
204
  - v0.5.1: Documentation, LobeHub manifest, and MCP Registry metadata synchronized; `robots.txt` served on the transport host
package/build/http.js CHANGED
@@ -2,9 +2,9 @@
2
2
  import { createHash } from "node:crypto";
3
3
  import { pathToFileURL } from "node:url";
4
4
  import { hostHeaderValidation, originValidation, toNodeHandler, } from "@modelcontextprotocol/node";
5
- import { createMcpHandler, } from "@modelcontextprotocol/server";
5
+ import { createMcpHandler, INTERNAL_ERROR, PARSE_ERROR, } from "@modelcontextprotocol/server";
6
6
  import express from "express";
7
- import { createMcpServer } from "./server.js";
7
+ import { createMcpServer, unauthenticatedCredential, UNAUTHENTICATED, } from "./server.js";
8
8
  import { ALL_TOOLS } from "./tools/index.js";
9
9
  import { PACKAGE_VERSION } from "./version.js";
10
10
  import { log } from "./utils.js";
@@ -13,6 +13,26 @@ const DEFAULT_AUTHORIZATION_SERVER = "https://clerk.s1.dev";
13
13
  const OAUTH_DISCOVERY_CACHE_CONTROL = "public, max-age=60, s-maxage=60";
14
14
  const MCP_RESOURCE = "https://mcp.search1api.com/mcp";
15
15
  const MCP_RESOURCE_METADATA = "https://mcp.search1api.com/.well-known/oauth-protected-resource/mcp";
16
+ /**
17
+ * JSON-RPC methods that only return static server metadata.
18
+ *
19
+ * The tool and resource descriptors are already published in the repository
20
+ * manifests, the server card, and the MCP registry, so answering them for an
21
+ * anonymous caller discloses nothing new and lets directory scanners enumerate
22
+ * the server without first completing an OAuth exchange. Every method that
23
+ * spends credits or reaches the Search1API backend is deliberately absent.
24
+ */
25
+ const PUBLIC_MCP_METHODS = new Set([
26
+ "initialize",
27
+ "notifications/initialized",
28
+ "ping",
29
+ "server/discover",
30
+ "tools/list",
31
+ "prompts/list",
32
+ "resources/list",
33
+ "resources/templates/list",
34
+ "resources/read",
35
+ ]);
16
36
  /**
17
37
  * Validate both Clerk OAuth tokens and legacy Search1API API keys at the API.
18
38
  */
@@ -44,8 +64,10 @@ export async function validateCredential(credential) {
44
64
  * Build the HTTP application without starting a listener.
45
65
  *
46
66
  * A single v2 handler serves the 2026-07-28 protocol and the SDK's default
47
- * stateless 2025 fallback. Authentication is validated for every exchange,
48
- * so no credential or principal is retained in a server-side MCP session.
67
+ * stateless 2025 fallback. Every presented credential is validated per
68
+ * exchange, so no credential or principal is retained in a server-side MCP
69
+ * session. An exchange that presents no credential at all reaches only the
70
+ * metadata methods in PUBLIC_MCP_METHODS.
49
71
  */
50
72
  export function createHttpApp(options = {}) {
51
73
  const app = express();
@@ -57,7 +79,7 @@ export function createHttpApp(options = {}) {
57
79
  const allowedOriginHostnames = options.allowedOriginHostnames ?? configuredAllowedOriginHostnames();
58
80
  const validateHost = hostHeaderValidation(allowedHostnames);
59
81
  const validateOrigin = originValidation(allowedOriginHostnames);
60
- const mcpHandler = createMcpHandler(({ authInfo }) => createMcpServer(authInfo?.token), {
82
+ const mcpHandler = createMcpHandler(({ authInfo }) => createMcpServer(toolCredential(authInfo)), {
61
83
  legacy: "stateless",
62
84
  onerror: (error) => log("MCP handler error:", error),
63
85
  });
@@ -81,9 +103,9 @@ export function createHttpApp(options = {}) {
81
103
  }
82
104
  res.redirect(301, target.toString());
83
105
  });
84
- // /mcp is a transport endpoint that answers unauthenticated crawlers with
85
- // 401, so search engines gain nothing from walking this host. Keep the OAuth
86
- // discovery documents reachable for agents.
106
+ // /mcp is a transport endpoint whose only anonymous answers are static
107
+ // descriptors, so search engines gain nothing from walking this host. Keep
108
+ // the OAuth discovery documents reachable for agents.
87
109
  app.get("/robots.txt", (_req, res) => {
88
110
  res
89
111
  .type("text/plain")
@@ -106,9 +128,10 @@ export function createHttpApp(options = {}) {
106
128
  .type("application/json")
107
129
  .json(protectedResourceMetadata);
108
130
  });
109
- // /mcp answers unauthenticated callers with 401 by design, so this card is
110
- // the only pre-connection description of the server. It is built from
111
- // ALL_TOOLS, so the advertised tool surface cannot drift from the real one.
131
+ // A single static document for directories that read one URL rather than
132
+ // speak MCP. /mcp now answers tools/list anonymously too, so this card is a
133
+ // convenience rather than the only pre-connection description. It is built
134
+ // from ALL_TOOLS, so neither surface can drift from the real tool set.
112
135
  app.get("/.well-known/mcp/server-card.json", (_req, res) => {
113
136
  res
114
137
  .set("Cache-Control", OAUTH_DISCOVERY_CACHE_CONTROL)
@@ -159,18 +182,42 @@ export function createHttpApp(options = {}) {
159
182
  });
160
183
  app.use(express.json());
161
184
  app.all("/mcp", async (req, res) => {
162
- const authenticated = await authenticateMcpRequest(req, res, credentialValidator);
163
- if (!authenticated) {
185
+ const outcome = await authenticateMcpRequest(req, res, credentialValidator, isPublicDiscovery(req));
186
+ if (outcome.status === "handled") {
164
187
  return;
165
188
  }
166
- const authInfo = {
167
- token: authenticated.credential,
168
- clientId: authenticated.principal,
169
- scopes: [],
170
- };
171
- req.auth = authInfo;
189
+ if (outcome.status === "authenticated") {
190
+ const authInfo = {
191
+ token: outcome.credential.credential,
192
+ clientId: outcome.credential.principal,
193
+ scopes: [],
194
+ };
195
+ req.auth = authInfo;
196
+ }
172
197
  await nodeHandler(req, res, req.body);
173
198
  });
199
+ // Express renders an HTML page for anything that fails before a route runs --
200
+ // most often body-parser rejecting a malformed or oversized payload. MCP
201
+ // clients and directory validators only parse JSON-RPC, so shape it here.
202
+ app.use("/mcp", (error, _req, res, next) => {
203
+ if (res.headersSent) {
204
+ next(error);
205
+ return;
206
+ }
207
+ log("MCP request rejected before dispatch:", error);
208
+ const status = error.status ?? error.statusCode ?? 500;
209
+ const clientError = status >= 400 && status < 500;
210
+ res.status(clientError ? status : 500).json({
211
+ jsonrpc: "2.0",
212
+ error: {
213
+ code: clientError ? PARSE_ERROR : INTERNAL_ERROR,
214
+ message: clientError
215
+ ? "The request body is not a valid JSON-RPC message."
216
+ : "The MCP request could not be processed.",
217
+ },
218
+ id: null,
219
+ });
220
+ });
174
221
  return {
175
222
  app,
176
223
  mcpHandler,
@@ -261,16 +308,72 @@ function challenge(res, message, error) {
261
308
  res.set("WWW-Authenticate", `Bearer resource_metadata="${MCP_RESOURCE_METADATA}"${errorParameter}`);
262
309
  res.status(401).json({
263
310
  jsonrpc: "2.0",
264
- error: { code: -32001, message },
311
+ error: { code: UNAUTHENTICATED, message },
265
312
  id: null,
266
313
  });
267
314
  }
268
- async function authenticateMcpRequest(req, res, credentialValidator) {
315
+ /**
316
+ * Resolve the credential a tool handler is allowed to spend.
317
+ *
318
+ * Anonymous exchanges only ever reach metadata methods, so no tool handler
319
+ * should observe one. Should a future routing change let a call through, fail
320
+ * loudly here rather than let makeRequest fall back to the operator's own
321
+ * SEARCH1API_KEY and bill an unauthenticated caller to us.
322
+ */
323
+ function toolCredential(authInfo) {
324
+ if (authInfo?.token) {
325
+ return authInfo.token;
326
+ }
327
+ return unauthenticatedCredential("Authentication is required to call Search1API tools.");
328
+ }
329
+ /**
330
+ * Collect every JSON-RPC method named by one HTTP exchange.
331
+ *
332
+ * The 2026-07-28 transport routes on the mcp-method header while the body
333
+ * repeats the method, and a legacy batch names one per array entry; all of them
334
+ * have to be public for the exchange to be. Returns null when any part of the
335
+ * request names no method, so an unrecognised shape falls through to the
336
+ * authenticated path instead of being mistaken for discovery.
337
+ */
338
+ function requestedMcpMethods(req) {
339
+ const methods = [];
340
+ const headerMethod = req.headers["mcp-method"];
341
+ if (typeof headerMethod === "string" && headerMethod.trim()) {
342
+ methods.push(headerMethod.trim());
343
+ }
344
+ const entries = Array.isArray(req.body) ? req.body : [req.body];
345
+ for (const entry of entries) {
346
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
347
+ return null;
348
+ }
349
+ const method = entry.method;
350
+ if (typeof method !== "string" || !method) {
351
+ return null;
352
+ }
353
+ methods.push(method);
354
+ }
355
+ return methods.length > 0 ? methods : null;
356
+ }
357
+ /** Whether this exchange may be served without any credential at all. */
358
+ function isPublicDiscovery(req) {
359
+ if (req.method !== "POST") {
360
+ return false;
361
+ }
362
+ const methods = requestedMcpMethods(req);
363
+ return (methods !== null && methods.every((method) => PUBLIC_MCP_METHODS.has(method)));
364
+ }
365
+ async function authenticateMcpRequest(req, res, credentialValidator, allowAnonymous) {
269
366
  const credential = extractCredential(req);
270
367
  if (!credential) {
368
+ if (allowAnonymous) {
369
+ return { status: "anonymous" };
370
+ }
271
371
  challenge(res, "Authentication is required. Use OAuth 2.1 discovery or provide a Search1API API key as a Bearer token.");
272
- return null;
372
+ return { status: "handled" };
273
373
  }
374
+ // A presented credential is validated even on a discovery method, so an
375
+ // expired token still draws the OAuth challenge when a client reconnects
376
+ // rather than surfacing as a failed tool call later in the session.
274
377
  let authenticated;
275
378
  try {
276
379
  authenticated = await credentialValidator(credential);
@@ -285,13 +388,13 @@ async function authenticateMcpRequest(req, res, credentialValidator) {
285
388
  },
286
389
  id: null,
287
390
  });
288
- return null;
391
+ return { status: "handled" };
289
392
  }
290
393
  if (!authenticated) {
291
394
  challenge(res, "The Bearer credential is invalid or expired.", "invalid_token");
292
- return null;
395
+ return { status: "handled" };
293
396
  }
294
- return authenticated;
397
+ return { status: "authenticated", credential: authenticated };
295
398
  }
296
399
  function installGlobalErrorLogging() {
297
400
  process.on("uncaughtException", (error) => {
package/build/index.js CHANGED
@@ -1,15 +1,19 @@
1
1
  #!/usr/bin/env node
2
2
  import { serveStdio } from "@modelcontextprotocol/server/stdio";
3
3
  import { API_KEY } from "./config.js";
4
- import { createMcpServer } from "./server.js";
4
+ import { createMcpServer, unauthenticatedCredential } from "./server.js";
5
5
  import { log } from "./utils.js";
6
6
  function main() {
7
+ // Serve even without a key: clients and directory tooling routinely probe a
8
+ // freshly installed package for its tool list before any credential is
9
+ // configured, and exiting here leaves them with a dead pipe rather than an
10
+ // answer. Tool calls still refuse until SEARCH1API_KEY is set.
7
11
  if (!API_KEY) {
8
- log("SEARCH1API_KEY environment variable is not set");
9
- process.exit(1);
12
+ log("SEARCH1API_KEY is not set; serving tool metadata only. Set it to run searches.");
10
13
  }
11
14
  log("Starting Search1API MCP server (stdio mode)");
12
- const handle = serveStdio(() => createMcpServer(API_KEY), {
15
+ const handle = serveStdio(() => createMcpServer(API_KEY ??
16
+ unauthenticatedCredential("SEARCH1API_KEY is not set. Set it in the server environment to call Search1API tools.")), {
13
17
  legacy: "serve",
14
18
  onerror: (error) => log("MCP stdio error:", error),
15
19
  });
package/build/server.js CHANGED
@@ -4,6 +4,21 @@ import { handleToolCall } from "./tools/handlers.js";
4
4
  import { ALL_TOOLS } from "./tools/index.js";
5
5
  import { formatError, log } from "./utils.js";
6
6
  import { PACKAGE_VERSION } from "./version.js";
7
+ /** JSON-RPC error code this server uses for a missing or rejected credential. */
8
+ export const UNAUTHENTICATED = -32001;
9
+ /**
10
+ * Build a credential provider that refuses instead of resolving.
11
+ *
12
+ * Both entry points serve tool metadata without a credential, so a tool handler
13
+ * can be reached with nothing to spend. Refusing here keeps makeRequest from
14
+ * falling back to the operator's own SEARCH1API_KEY and billing an
15
+ * unauthenticated caller's search to us.
16
+ */
17
+ export function unauthenticatedCredential(message) {
18
+ return () => {
19
+ throw new ProtocolError(UNAUTHENTICATED, message);
20
+ };
21
+ }
7
22
  /**
8
23
  * Create one transport-neutral MCP server instance.
9
24
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "search1api-mcp",
3
- "version": "0.5.4",
3
+ "version": "0.6.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,
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.5.3",
10
+ "version": "0.6.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.5.3",
21
+ "version": "0.6.0",
22
22
  "transport": {
23
23
  "type": "stdio"
24
24
  },