search1api-mcp 0.5.3 → 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
@@ -5,12 +5,13 @@
5
5
 
6
6
  [中文文档](./README_zh.md)
7
7
 
8
- The official MCP server for [Search1API](https://www.search1api.com/?utm_source=mcp) — web search, news, page retrieval, sitemap discovery, and trending topics in one API.
8
+ The official MCP server for [Search1API](https://s1.dev/?utm_source=mcp) — web search, news, page retrieval, sitemap discovery, and trending topics in one API.
9
9
 
10
10
  ## Authentication
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
 
@@ -53,6 +54,12 @@ https://mcp.search1api.com/mcp?apiKey=YOUR_SEARCH1API_KEY
53
54
 
54
55
  ### Cursor
55
56
 
57
+ Install as a Cursor plugin (recommended): this repo includes Agent Plugins `plugin.json` + `mcp.json` (portable) and `.cursor-plugin/plugin.json` (Cursor Marketplace metadata / logo) for Remote MCP with OAuth. Submit or install from [cursor.directory](https://cursor.directory) / the Cursor Marketplace, then sign in when prompted.
58
+
59
+ For local testing, copy the plugin files into `~/.cursor/plugins/local/search1api` (`plugin.json`, `.cursor-plugin/`, `mcp.json`, `assets/`). Do not symlink from outside that directory — Cursor rejects external symlink targets.
60
+
61
+ Or configure manually:
62
+
56
63
  ```json
57
64
  {
58
65
  "mcpServers": {
@@ -190,6 +197,8 @@ Get trending topics from popular platforms.
190
197
 
191
198
  ## Version History
192
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
193
202
  - v0.5.3: OAuth resource and tool metadata no longer require OIDC session scopes; Smithery and Glama registry badges added
194
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`
195
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,14 +2,37 @@
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
+ import { ALL_TOOLS } from "./tools/index.js";
9
+ import { PACKAGE_VERSION } from "./version.js";
8
10
  import { log } from "./utils.js";
9
11
  const API_BASE_URL = process.env.SEARCH1API_API_URL || "https://api.search1api.com";
10
- const AUTHORIZATION_SERVER = "https://clerk.search1api.com";
12
+ const DEFAULT_AUTHORIZATION_SERVER = "https://clerk.s1.dev";
13
+ const OAUTH_DISCOVERY_CACHE_CONTROL = "public, max-age=60, s-maxage=60";
11
14
  const MCP_RESOURCE = "https://mcp.search1api.com/mcp";
12
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
+ ]);
13
36
  /**
14
37
  * Validate both Clerk OAuth tokens and legacy Search1API API keys at the API.
15
38
  */
@@ -41,17 +64,22 @@ export async function validateCredential(credential) {
41
64
  * Build the HTTP application without starting a listener.
42
65
  *
43
66
  * 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.
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.
46
71
  */
47
72
  export function createHttpApp(options = {}) {
48
73
  const app = express();
49
74
  const credentialValidator = options.validateCredential ?? validateCredential;
75
+ const authorizationServer = normalizeAuthorizationServer(options.authorizationServer ??
76
+ process.env.OAUTH_AUTHORIZATION_SERVER ??
77
+ DEFAULT_AUTHORIZATION_SERVER);
50
78
  const allowedHostnames = options.allowedHostnames ?? configuredAllowedHostnames();
51
79
  const allowedOriginHostnames = options.allowedOriginHostnames ?? configuredAllowedOriginHostnames();
52
80
  const validateHost = hostHeaderValidation(allowedHostnames);
53
81
  const validateOrigin = originValidation(allowedOriginHostnames);
54
- const mcpHandler = createMcpHandler(({ authInfo }) => createMcpServer(authInfo?.token), {
82
+ const mcpHandler = createMcpHandler(({ authInfo }) => createMcpServer(toolCredential(authInfo)), {
55
83
  legacy: "stateless",
56
84
  onerror: (error) => log("MCP handler error:", error),
57
85
  });
@@ -67,7 +95,7 @@ export function createHttpApp(options = {}) {
67
95
  // The service root is documentation, not an MCP transport endpoint. Keep
68
96
  // query parameters so bookmarked campaign/support links remain attributable.
69
97
  app.get("/", (req, res) => {
70
- const target = new URL("https://www.search1api.com/docs/integrations/mcp");
98
+ const target = new URL("https://s1.dev/docs/integrations/mcp");
71
99
  for (const [key, value] of Object.entries(req.query)) {
72
100
  if (typeof value === "string") {
73
101
  target.searchParams.append(key, value);
@@ -75,9 +103,9 @@ export function createHttpApp(options = {}) {
75
103
  }
76
104
  res.redirect(301, target.toString());
77
105
  });
78
- // /mcp is a transport endpoint that answers unauthenticated crawlers with
79
- // 401, so search engines gain nothing from walking this host. Keep the OAuth
80
- // 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.
81
109
  app.get("/robots.txt", (_req, res) => {
82
110
  res
83
111
  .type("text/plain")
@@ -87,18 +115,64 @@ export function createHttpApp(options = {}) {
87
115
  // exchange; this resource does not require any resource-specific scope.
88
116
  const protectedResourceMetadata = {
89
117
  resource: MCP_RESOURCE,
90
- authorization_servers: [AUTHORIZATION_SERVER],
118
+ authorization_servers: [authorizationServer],
91
119
  bearer_methods_supported: ["header"],
92
- resource_documentation: "https://www.search1api.com/auth.md",
120
+ resource_documentation: "https://s1.dev/auth.md",
93
121
  };
94
122
  app.get([
95
123
  "/.well-known/oauth-protected-resource",
96
124
  "/.well-known/oauth-protected-resource/mcp",
97
125
  ], (_req, res) => {
98
- res.type("application/json").json(protectedResourceMetadata);
126
+ res
127
+ .set("Cache-Control", OAUTH_DISCOVERY_CACHE_CONTROL)
128
+ .type("application/json")
129
+ .json(protectedResourceMetadata);
130
+ });
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.
135
+ app.get("/.well-known/mcp/server-card.json", (_req, res) => {
136
+ res
137
+ .set("Cache-Control", OAUTH_DISCOVERY_CACHE_CONTROL)
138
+ .type("application/json")
139
+ .json({
140
+ name: "Search1API",
141
+ version: PACKAGE_VERSION,
142
+ description: "Remote MCP server for Search1API. Exposes live web search, news, page reading, sitemap discovery, and trending topics as tools for AI agents.",
143
+ serverUrl: MCP_RESOURCE,
144
+ tools: ALL_TOOLS.map((tool) => ({
145
+ name: tool.name,
146
+ title: tool.title,
147
+ description: tool.description,
148
+ inputSchema: tool.inputSchema,
149
+ annotations: tool.annotations,
150
+ })),
151
+ serverInfo: {
152
+ name: "Search1API",
153
+ title: "Search1API MCP",
154
+ version: PACKAGE_VERSION,
155
+ },
156
+ protocolVersion: "2025-06-18",
157
+ transport: { type: "streamable-http", endpoint: MCP_RESOURCE },
158
+ capabilities: { tools: {} },
159
+ authentication: {
160
+ type: "oauth2",
161
+ protectedResourceMetadata: MCP_RESOURCE_METADATA,
162
+ authorizationServerMetadata: `${authorizationServer}/.well-known/oauth-authorization-server`,
163
+ legacyApiKey: {
164
+ supported: true,
165
+ method: "Authorization: Bearer SEARCH1API_KEY",
166
+ },
167
+ },
168
+ homepage: "https://s1.dev",
169
+ documentation: "https://s1.dev/docs",
170
+ });
99
171
  });
100
172
  app.get("/.well-known/oauth-authorization-server", (_req, res) => {
101
- res.redirect(302, `${AUTHORIZATION_SERVER}/.well-known/oauth-authorization-server`);
173
+ res
174
+ .set("Cache-Control", OAUTH_DISCOVERY_CACHE_CONTROL)
175
+ .redirect(302, `${authorizationServer}/.well-known/oauth-authorization-server`);
102
176
  });
103
177
  app.use("/mcp", (req, res, next) => {
104
178
  if (!validateOrigin(req, res)) {
@@ -108,24 +182,61 @@ export function createHttpApp(options = {}) {
108
182
  });
109
183
  app.use(express.json());
110
184
  app.all("/mcp", async (req, res) => {
111
- const authenticated = await authenticateMcpRequest(req, res, credentialValidator);
112
- if (!authenticated) {
185
+ const outcome = await authenticateMcpRequest(req, res, credentialValidator, isPublicDiscovery(req));
186
+ if (outcome.status === "handled") {
113
187
  return;
114
188
  }
115
- const authInfo = {
116
- token: authenticated.credential,
117
- clientId: authenticated.principal,
118
- scopes: [],
119
- };
120
- 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
+ }
121
197
  await nodeHandler(req, res, req.body);
122
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
+ });
123
221
  return {
124
222
  app,
125
223
  mcpHandler,
126
224
  close: () => mcpHandler.close(),
127
225
  };
128
226
  }
227
+ function normalizeAuthorizationServer(value) {
228
+ const url = new URL(value.trim());
229
+ const isHttpsOrigin = url.protocol === "https:" &&
230
+ !url.username &&
231
+ !url.password &&
232
+ url.pathname === "/" &&
233
+ !url.search &&
234
+ !url.hash;
235
+ if (!isHttpsOrigin) {
236
+ throw new Error("OAUTH_AUTHORIZATION_SERVER must be a valid HTTPS origin");
237
+ }
238
+ return url.origin;
239
+ }
129
240
  function configuredAllowedHostnames() {
130
241
  const configured = (process.env.MCP_ALLOWED_HOSTS ?? "")
131
242
  .split(",")
@@ -197,16 +308,72 @@ function challenge(res, message, error) {
197
308
  res.set("WWW-Authenticate", `Bearer resource_metadata="${MCP_RESOURCE_METADATA}"${errorParameter}`);
198
309
  res.status(401).json({
199
310
  jsonrpc: "2.0",
200
- error: { code: -32001, message },
311
+ error: { code: UNAUTHENTICATED, message },
201
312
  id: null,
202
313
  });
203
314
  }
204
- 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) {
205
366
  const credential = extractCredential(req);
206
367
  if (!credential) {
368
+ if (allowAnonymous) {
369
+ return { status: "anonymous" };
370
+ }
207
371
  challenge(res, "Authentication is required. Use OAuth 2.1 discovery or provide a Search1API API key as a Bearer token.");
208
- return null;
372
+ return { status: "handled" };
209
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.
210
377
  let authenticated;
211
378
  try {
212
379
  authenticated = await credentialValidator(credential);
@@ -221,13 +388,13 @@ async function authenticateMcpRequest(req, res, credentialValidator) {
221
388
  },
222
389
  id: null,
223
390
  });
224
- return null;
391
+ return { status: "handled" };
225
392
  }
226
393
  if (!authenticated) {
227
394
  challenge(res, "The Bearer credential is invalid or expired.", "invalid_token");
228
- return null;
395
+ return { status: "handled" };
229
396
  }
230
- return authenticated;
397
+ return { status: "authenticated", credential: authenticated };
231
398
  }
232
399
  function installGlobalErrorLogging() {
233
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.3",
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,
@@ -48,7 +48,7 @@
48
48
  "type": "git",
49
49
  "url": "git+https://github.com/superagents-lab/search1api-mcp.git"
50
50
  },
51
- "homepage": "https://github.com/superagents-lab/search1api-mcp#readme",
51
+ "homepage": "https://s1.dev",
52
52
  "bugs": {
53
53
  "url": "https://github.com/superagents-lab/search1api-mcp/issues"
54
54
  },
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
  },