@nite07/websearch-mcp 0.1.4 → 0.2.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 +46 -0
- package/README.zh.md +38 -0
- package/dist/live.d.ts +21 -0
- package/dist/live.js +52 -0
- package/dist/main.js +217 -37
- package/dist/sdk.d.ts +21 -0
- package/dist/sdk.js +88 -0
- package/dist/tools.d.ts +2 -1
- package/dist/tools.js +20 -4
- package/dist/ui/embedded.d.ts +20 -0
- package/dist/ui/embedded.js +14 -0
- package/dist/ui/page.d.ts +2 -0
- package/dist/ui/page.html +694 -0
- package/dist/ui/page.js +15 -0
- package/dist/ui/server.d.ts +21 -0
- package/dist/ui/server.js +243 -0
- package/dist/ui/session.d.ts +38 -0
- package/dist/ui/session.js +111 -0
- package/dist/ui/state.d.ts +62 -0
- package/dist/ui/state.js +256 -0
- package/dist/ui/token.d.ts +23 -0
- package/dist/ui/token.js +23 -0
- package/package.json +3 -2
- package/dist/protocol.d.ts +0 -19
- package/dist/protocol.js +0 -125
package/README.md
CHANGED
|
@@ -2,6 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
English | [中文](README.zh.md)
|
|
4
4
|
|
|
5
|
+
[](https://www.npmjs.com/package/@nite07/websearch-mcp)
|
|
6
|
+
[](https://www.npmjs.com/package/@nite07/websearch-mcp)
|
|
7
|
+
|
|
5
8
|
An MCP server for multi-backend web search, plus discussion reading for Reddit and X and note reading
|
|
6
9
|
for Xiaohongshu. Works with any
|
|
7
10
|
MCP client: Claude Code, Codex, DeepSeek Harness, or your own.
|
|
@@ -34,6 +37,42 @@ and Reddit, which need no account.
|
|
|
34
37
|
`list_backends` first: it reports each backend's modes, cost tier, enabled state and whether a
|
|
35
38
|
credential is present. It never enables anything.
|
|
36
39
|
|
|
40
|
+
## Settings page
|
|
41
|
+
|
|
42
|
+
The configuration has a page: every backend, its access mode, its cost tier, its options and its
|
|
43
|
+
credential in one form, plus a probe button per backend. **The MCP server serves it itself** — one
|
|
44
|
+
process, no extra unit, container or port-forwarder to install:
|
|
45
|
+
|
|
46
|
+
```sh
|
|
47
|
+
WEBSEARCH_MCP_UI_PORT=7799 WEBSEARCH_MCP_UI_TOKEN=... websearch-mcp # stdio client + page
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
- `WEBSEARCH_MCP_UI_PORT` turns the page on for that process; `WEBSEARCH_MCP_UI_HOST` picks the bind
|
|
51
|
+
address (default `127.0.0.1`, so a client on the same machine needs nothing else).
|
|
52
|
+
- The page lives exactly as long as the server does. When the client closes stdin the process exits
|
|
53
|
+
and the port is released, which also means a client that respawns the server gets a fresh page.
|
|
54
|
+
- A port that cannot be bound is reported on stderr and the MCP tools carry on: a page is never a
|
|
55
|
+
reason to lose the tools.
|
|
56
|
+
- **Authentication is on only when a token is supplied, and the token comes from the environment or
|
|
57
|
+
the command line — this server never writes one to disk.** `--no-token` (page-only mode) or
|
|
58
|
+
`WEBSEARCH_MCP_UI_TOKEN` (any mode) decides it; with neither, the page is open and the log says so.
|
|
59
|
+
- With a token the first request carries `?token=`, exchanged for an `HttpOnly`, `SameSite=Strict`
|
|
60
|
+
cookie, so the link does not stay in browser history.
|
|
61
|
+
- Saving validates against the same schema the server enforces. A rejected save leaves the file
|
|
62
|
+
untouched and lists every problem by path; an accepted one writes `config.json.bak-<local time>`
|
|
63
|
+
(five kept) and replaces the file atomically at mode 0600. The server watching that file reloads
|
|
64
|
+
immediately, so the next `web_search` already uses what the page saved.
|
|
65
|
+
- A file that stops parsing keeps the previous configuration and says why on stderr.
|
|
66
|
+
- When a `config.container.json` sits beside the file, every save rewrites it too: loopback endpoints
|
|
67
|
+
become `host.containers.internal`, and the browser session file is mapped into `/host/home`. The
|
|
68
|
+
companion is never created on its own.
|
|
69
|
+
|
|
70
|
+
Page without an MCP client, for a quick look:
|
|
71
|
+
|
|
72
|
+
```sh
|
|
73
|
+
websearch-mcp --ui --host 0.0.0.0 --port 7799 --print-url # --print-url prints the links and exits
|
|
74
|
+
```
|
|
75
|
+
|
|
37
76
|
## Client configuration
|
|
38
77
|
|
|
39
78
|
```json
|
|
@@ -121,6 +160,13 @@ or a missing note token is reported instead of an empty note. |
|
|
|
121
160
|
`compact: true` returns URL, title and date only, which is usually the difference between a usable
|
|
122
161
|
context and a flooded one.
|
|
123
162
|
|
|
163
|
+
## Protocol versions
|
|
164
|
+
|
|
165
|
+
The wire protocol is the [official TypeScript SDK](https://ts.sdk.modelcontextprotocol.io/v2/)
|
|
166
|
+
(`@modelcontextprotocol/server`), not a hand-written loop: the server answers the stateless
|
|
167
|
+
`2026-07-28` revision and falls back to the 2025 handshake for clients that still open with
|
|
168
|
+
`initialize`. A protocol revision therefore reaches this package as a dependency bump.
|
|
169
|
+
|
|
124
170
|
## Behaviour worth relying on
|
|
125
171
|
|
|
126
172
|
- **No fallback.** A backend uses the mode you selected, the credential you gave it and the endpoint in
|
package/README.zh.md
CHANGED
|
@@ -2,6 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
[English](README.md) | 中文
|
|
4
4
|
|
|
5
|
+
[](https://www.npmjs.com/package/@nite07/websearch-mcp)
|
|
6
|
+
[](https://www.npmjs.com/package/@nite07/websearch-mcp)
|
|
7
|
+
|
|
5
8
|
一个多后端网页搜索的 MCP 服务,另外能读 Reddit 和 X 的讨论帖,以及小红书的笔记。任何 MCP 客户端都能用:Claude Code、Codex、DeepSeek Harness,或者你自己写的。
|
|
6
9
|
|
|
7
10
|
## 为什么还要一个搜索 MCP
|
|
@@ -26,6 +29,35 @@ websearch-mcp --print-config > ~/.config/websearch-mcp/config.json
|
|
|
26
29
|
|
|
27
30
|
想先看看有什么可用又不花钱,调 `list_backends`:它列出每个后端的模式、费用档、启用状态以及有没有凭证,但不会启用任何东西。
|
|
28
31
|
|
|
32
|
+
## 配置页面
|
|
33
|
+
|
|
34
|
+
配置有页面了:每个后端的接入模式、成本档位、选项与凭证都在同一张表里,每张卡片带一个实测按钮。
|
|
35
|
+
**这个页面由 MCP 服务器自己提供**——一个进程,不需要额外的单元、容器或端口转发:
|
|
36
|
+
|
|
37
|
+
```sh
|
|
38
|
+
WEBSEARCH_MCP_UI_PORT=7799 WEBSEARCH_MCP_UI_TOKEN=... websearch-mcp # stdio 服务 + 页面
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
- `WEBSEARCH_MCP_UI_PORT` 打开页面,`WEBSEARCH_MCP_UI_HOST` 选绑定地址(默认 `127.0.0.1`,
|
|
42
|
+
同机客户端什么都不用加)。
|
|
43
|
+
- 页面活多久取决于服务活多久。客户端关掉 stdin,进程退出、端口释放;客户端重新拉起服务,页面也就跟着回来。
|
|
44
|
+
- 端口绑不上时只在 stderr 报一句,MCP 工具照常工作——页面永远不该成为丢工具的理由。
|
|
45
|
+
- **只有给了令牌才鉴权,令牌只从环境变量或命令行来——服务绝不往磁盘写令牌。** 页面模式也可以用
|
|
46
|
+
`--no-token`;两者都没有时页面是开放的,日志会说明。
|
|
47
|
+
- 有令牌时第一个请求带 `?token=`,换成 `HttpOnly` + `SameSite=Strict` 的 cookie,链接不留在浏览器历史里。
|
|
48
|
+
- 保存用服务端同一套 schema 校验。被拒的保存不动文件,按字段路径列出问题;通过的保存先写
|
|
49
|
+
`config.json.bak-<本地时间>`(保留 5 份),再原子替换并设为 0600。服务一直在 watch 这个文件,
|
|
50
|
+
所以保存完下一次 `web_search` 就用新配置。
|
|
51
|
+
- 文件解析不了时保留上一份可用配置,并在 stderr 说明原因。
|
|
52
|
+
- 配置旁边如果有 `config.container.json`,每次保存会连它一起重写:loopback 端点换成
|
|
53
|
+
`host.containers.internal`,浏览器登录态文件映射到 `/host/home`。没有这个文件就不会凭空创建。
|
|
54
|
+
|
|
55
|
+
不想起 MCP 客户端、只想看一眼页面:
|
|
56
|
+
|
|
57
|
+
```sh
|
|
58
|
+
websearch-mcp --ui --host 0.0.0.0 --port 7799 --print-url # --print-url 只打印链接
|
|
59
|
+
```
|
|
60
|
+
|
|
29
61
|
## 客户端配置
|
|
30
62
|
|
|
31
63
|
```json
|
|
@@ -96,6 +128,12 @@ websearch-mcp --print-config > ~/.config/websearch-mcp/config.json
|
|
|
96
128
|
|
|
97
129
|
`compact: true` 只回 URL、标题和日期,通常就是一个还能用的上下文和一个被灌满的上下文的区别。
|
|
98
130
|
|
|
131
|
+
## 协议版本
|
|
132
|
+
|
|
133
|
+
线上协议交给[官方 TypeScript SDK](https://ts.sdk.modelcontextprotocol.io/v2/)
|
|
134
|
+
(`@modelcontextprotocol/server`),不是手写循环:服务端会说无状态的 `2026-07-28`,对仍在用
|
|
135
|
+
`initialize` 开场的客户端回退到 2025 握手。协议改版因此是升依赖,不是重写连接层。
|
|
136
|
+
|
|
99
137
|
## 可以依赖的行为
|
|
100
138
|
|
|
101
139
|
- **不切换。** 后端只按你选定的模式、你给的凭证、配置里的端点工作。重试不会换服务商、不会换模式。
|
package/dist/live.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { type ServerConfig } from './config.js';
|
|
2
|
+
/**
|
|
3
|
+
* Tools read the configuration through this handle on every call instead of closing over a snapshot,
|
|
4
|
+
* so an edit that lands on disk reaches a server that is already running.
|
|
5
|
+
*/
|
|
6
|
+
export interface ConfigSource {
|
|
7
|
+
get(): ServerConfig;
|
|
8
|
+
/** Changes whenever the configuration behind get() changed; the search engine rebuilds on a new value. */
|
|
9
|
+
revision(): string;
|
|
10
|
+
}
|
|
11
|
+
export declare const fixedSource: (config: ServerConfig) => ConfigSource;
|
|
12
|
+
export declare function asSource(value: ServerConfig | ConfigSource): ConfigSource;
|
|
13
|
+
export interface ReloadableSource extends ConfigSource {
|
|
14
|
+
close(): void;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Watches the directory rather than the file: a settings page replaces the file by rename, which
|
|
18
|
+
* detaches a watcher bound to the inode. A failed reload keeps the previous configuration alive and
|
|
19
|
+
* says why, because a half-written file must never take the running server down.
|
|
20
|
+
*/
|
|
21
|
+
export declare function watchSource(initial: ServerConfig, log: (message: string) => void): ReloadableSource;
|
package/dist/live.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { watch } from 'node:fs';
|
|
2
|
+
import { basename, dirname } from 'node:path';
|
|
3
|
+
import { loadConfig } from './config.js';
|
|
4
|
+
export const fixedSource = (config) => ({ get: () => config, revision: () => 'fixed' });
|
|
5
|
+
export function asSource(value) {
|
|
6
|
+
return typeof value.get === 'function' ? value : fixedSource(value);
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Watches the directory rather than the file: a settings page replaces the file by rename, which
|
|
10
|
+
* detaches a watcher bound to the inode. A failed reload keeps the previous configuration alive and
|
|
11
|
+
* says why, because a half-written file must never take the running server down.
|
|
12
|
+
*/
|
|
13
|
+
export function watchSource(initial, log) {
|
|
14
|
+
let current = initial;
|
|
15
|
+
let revision = 0;
|
|
16
|
+
let timer;
|
|
17
|
+
let closed = false;
|
|
18
|
+
const directory = dirname(initial.configPath);
|
|
19
|
+
const name = basename(initial.configPath);
|
|
20
|
+
const watcher = watch(directory, { persistent: false }, (_event, filename) => {
|
|
21
|
+
if (filename && basename(String(filename)) !== name)
|
|
22
|
+
return;
|
|
23
|
+
if (timer)
|
|
24
|
+
clearTimeout(timer);
|
|
25
|
+
timer = setTimeout(() => void reload(), 150);
|
|
26
|
+
timer.unref?.();
|
|
27
|
+
});
|
|
28
|
+
watcher.on('error', error => log(`configuration watcher stopped: ${error instanceof Error ? error.message : String(error)}`));
|
|
29
|
+
async function reload() {
|
|
30
|
+
if (closed)
|
|
31
|
+
return;
|
|
32
|
+
try {
|
|
33
|
+
current = await loadConfig({ configPath: initial.configPath });
|
|
34
|
+
revision += 1;
|
|
35
|
+
log(`configuration reloaded from ${initial.configPath} (revision ${revision})`);
|
|
36
|
+
}
|
|
37
|
+
catch (error) {
|
|
38
|
+
const reason = error instanceof Error ? error.message.split('\n')[0] : String(error);
|
|
39
|
+
log(`configuration at ${initial.configPath} is not usable; keeping the previous one: ${reason}`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return {
|
|
43
|
+
get: () => current,
|
|
44
|
+
revision: () => `r${revision}`,
|
|
45
|
+
close: () => {
|
|
46
|
+
closed = true;
|
|
47
|
+
if (timer)
|
|
48
|
+
clearTimeout(timer);
|
|
49
|
+
watcher.close();
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
}
|
package/dist/main.js
CHANGED
|
@@ -1,49 +1,98 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
import { ConfigError, loadConfig, starterConfig } from './config.js';
|
|
4
|
-
import {
|
|
2
|
+
import { readFile } from 'node:fs/promises';
|
|
3
|
+
import { ConfigError, DEFAULT_CONFIG_PATH, loadConfig, starterConfig } from './config.js';
|
|
4
|
+
import { serveTools } from './sdk.js';
|
|
5
5
|
import { createTools } from './tools.js';
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
const
|
|
12
|
-
const
|
|
13
|
-
|
|
14
|
-
const
|
|
15
|
-
|
|
16
|
-
|
|
6
|
+
import { watchSource } from './live.js';
|
|
7
|
+
import { startUi, tokenUrls } from './ui/server.js';
|
|
8
|
+
import { decideToken, tokenIsShort } from './ui/token.js';
|
|
9
|
+
import { embeddedFromEnv } from './ui/embedded.js';
|
|
10
|
+
const DEFAULT_UI_HOST = '127.0.0.1';
|
|
11
|
+
const DEFAULT_UI_PORT = 7799;
|
|
12
|
+
const VALUE_FLAGS = new Set(['host', 'port', 'config', 'token', 'set-token']);
|
|
13
|
+
function parseArgs(argv) {
|
|
14
|
+
const flags = new Map();
|
|
15
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
16
|
+
const argument = argv[index];
|
|
17
|
+
if (argument === '-h') {
|
|
18
|
+
flags.set('h', true);
|
|
19
|
+
continue;
|
|
20
|
+
}
|
|
21
|
+
if (!argument.startsWith('--'))
|
|
22
|
+
continue;
|
|
23
|
+
const equals = argument.indexOf('=');
|
|
24
|
+
if (equals > 0) {
|
|
25
|
+
flags.set(argument.slice(2, equals), argument.slice(equals + 1));
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
const name = argument.slice(2);
|
|
29
|
+
if (VALUE_FLAGS.has(name) && index + 1 < argv.length)
|
|
30
|
+
flags.set(name, argv[++index]);
|
|
31
|
+
else
|
|
32
|
+
flags.set(name, true);
|
|
33
|
+
}
|
|
34
|
+
return flags;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* The manifest beside dist is the authority. npm_package_version is inherited from whatever started
|
|
38
|
+
* this process, and a host like an MCP gateway sets it to its own version.
|
|
39
|
+
*/
|
|
40
|
+
async function readVersion() {
|
|
41
|
+
try {
|
|
42
|
+
const text = await readFile(new URL('../package.json', import.meta.url), 'utf8');
|
|
43
|
+
const parsed = JSON.parse(text);
|
|
44
|
+
if (typeof parsed.version === 'string')
|
|
45
|
+
return parsed.version;
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
// A checkout without a manifest beside dist is still usable; the version is cosmetic.
|
|
49
|
+
}
|
|
50
|
+
return process.env.npm_package_version ?? '0.1.0';
|
|
51
|
+
}
|
|
52
|
+
const help = () => `websearch-mcp — MCP server for multi-backend web search
|
|
17
53
|
|
|
18
54
|
Usage
|
|
19
|
-
websearch-mcp
|
|
20
|
-
websearch-mcp --
|
|
21
|
-
websearch-mcp --config
|
|
55
|
+
websearch-mcp run over stdio (what an MCP client spawns)
|
|
56
|
+
websearch-mcp --ui run only the settings page, without stdio
|
|
57
|
+
websearch-mcp --print-config print a starter configuration to stdout
|
|
58
|
+
websearch-mcp --print-url print the page URLs
|
|
59
|
+
|
|
60
|
+
Options
|
|
61
|
+
--config <path> configuration file (default ~/.config/websearch-mcp/config.json)
|
|
62
|
+
--host <addr> settings page bind address (default ${DEFAULT_UI_HOST}; 0.0.0.0 exposes it on every interface)
|
|
63
|
+
--port <n> settings page port (default ${DEFAULT_UI_PORT}, 0 picks a free one)
|
|
64
|
+
--token <value> require this token for this run
|
|
65
|
+
--no-token serve the page without authentication
|
|
66
|
+
|
|
67
|
+
Authentication
|
|
68
|
+
The token comes from --token or WEBSEARCH_MCP_UI_TOKEN, and from nowhere else: this process never
|
|
69
|
+
writes one to disk. With neither set the page is open, and the log says so: anyone who can reach
|
|
70
|
+
the port can rewrite the configuration.
|
|
22
71
|
|
|
23
72
|
Environment
|
|
24
|
-
WEBSEARCH_MCP_CONFIG
|
|
25
|
-
|
|
73
|
+
WEBSEARCH_MCP_CONFIG path to config.json (default ~/.config/websearch-mcp/config.json)
|
|
74
|
+
WEBSEARCH_MCP_UI_HOST bind address for the page (default 127.0.0.1)
|
|
75
|
+
WEBSEARCH_MCP_UI_PORT serve the page from this stdio process too, on this port
|
|
76
|
+
WEBSEARCH_MCP_UI_TOKEN the token to require, unless --token or --no-token is given
|
|
77
|
+
DSH_SEARCH_<BACKEND>_KEY a credential; wins over the value stored in the file
|
|
78
|
+
DSH_SEARCH_BROWSER_TOKEN the browser endpoint token
|
|
79
|
+
`;
|
|
80
|
+
const argv = process.argv.slice(2);
|
|
81
|
+
const flags = parseArgs(argv);
|
|
82
|
+
const configPath = typeof flags.get('config') === 'string'
|
|
83
|
+
? String(flags.get('config'))
|
|
84
|
+
: process.env.WEBSEARCH_MCP_CONFIG ?? DEFAULT_CONFIG_PATH;
|
|
85
|
+
if (flags.has('help') || flags.has('h')) {
|
|
86
|
+
process.stdout.write(help());
|
|
26
87
|
process.exit(0);
|
|
27
88
|
}
|
|
28
|
-
if (
|
|
89
|
+
if (flags.has('print-config')) {
|
|
29
90
|
process.stdout.write(`${JSON.stringify(starterConfig(), null, 2)}\n`);
|
|
30
91
|
process.exit(0);
|
|
31
92
|
}
|
|
32
|
-
// stdout is the protocol channel: diagnostics must never touch it.
|
|
93
|
+
// stdout is the protocol channel in stdio mode: diagnostics must never touch it.
|
|
33
94
|
const log = (message) => { process.stderr.write(`[websearch-mcp] ${message}\n`); };
|
|
34
|
-
const
|
|
35
|
-
for (const signal of ['SIGINT', 'SIGTERM'])
|
|
36
|
-
process.on(signal, () => { abort.abort(); process.exit(0); });
|
|
37
|
-
let protocol;
|
|
38
|
-
try {
|
|
39
|
-
const config = await loadConfig({ ...(configFlag ? { configPath: configFlag } : {}) });
|
|
40
|
-
const tools = createTools(config, identity);
|
|
41
|
-
protocol = createProtocol(tools, { name: identity.name, version: identity.version }, process.stdout);
|
|
42
|
-
log(`ready with ${tools.length} tools; config ${config.configPath}`);
|
|
43
|
-
}
|
|
44
|
-
catch (error) {
|
|
45
|
-
// The server still answers initialize/tools/list, but every search would fail, so say why on
|
|
46
|
-
// stderr and refuse to pretend: the client sees a clean exit instead of a half-working server.
|
|
95
|
+
const crash = (error) => {
|
|
47
96
|
if (error instanceof ConfigError) {
|
|
48
97
|
log(error.message);
|
|
49
98
|
for (const detail of error.details)
|
|
@@ -53,7 +102,138 @@ catch (error) {
|
|
|
53
102
|
log(error instanceof Error ? error.message : String(error));
|
|
54
103
|
}
|
|
55
104
|
process.exit(1);
|
|
105
|
+
};
|
|
106
|
+
function bindTarget() {
|
|
107
|
+
const host = typeof flags.get('host') === 'string' ? String(flags.get('host')) : process.env.WEBSEARCH_MCP_UI_HOST ?? DEFAULT_UI_HOST;
|
|
108
|
+
const raw = typeof flags.get('port') === 'string' ? String(flags.get('port')) : process.env.WEBSEARCH_MCP_UI_PORT ?? String(DEFAULT_UI_PORT);
|
|
109
|
+
const port = Number(raw);
|
|
110
|
+
if (!Number.isInteger(port) || port < 0 || port > 65535) {
|
|
111
|
+
log(`--port needs an integer between 0 and 65535, got ${raw}`);
|
|
112
|
+
process.exit(1);
|
|
113
|
+
}
|
|
114
|
+
return { host: host.trim() || DEFAULT_UI_HOST, port };
|
|
115
|
+
}
|
|
116
|
+
const identity = {
|
|
117
|
+
name: 'websearch-mcp',
|
|
118
|
+
version: await readVersion(),
|
|
119
|
+
projectUrl: 'https://git.nite07.com/nite/search/src/branch/main/packages/websearch-mcp',
|
|
120
|
+
};
|
|
121
|
+
function resolveToken() {
|
|
122
|
+
const decision = decideToken({
|
|
123
|
+
...(typeof flags.get('token') === 'string' ? { flag: String(flags.get('token')) } : {}),
|
|
124
|
+
...(flags.has('no-token') ? { open: true } : {}),
|
|
125
|
+
});
|
|
126
|
+
if (decision.token && tokenIsShort(decision.token)) {
|
|
127
|
+
log(`warning: a ${decision.token.length}-character token is guessable; use a random 32-byte value`);
|
|
128
|
+
}
|
|
129
|
+
log(`authentication: ${decision.token ? `token (${decision.source})` : 'disabled'}; ${decision.note}`);
|
|
130
|
+
return { ...(decision.token === undefined ? {} : { token: decision.token }), source: decision.source };
|
|
131
|
+
}
|
|
132
|
+
const openWarning = () => log('no token is configured, so the page is open: anyone who can reach it can rewrite the configuration');
|
|
133
|
+
/**
|
|
134
|
+
* stdio mode answers MCP tools; with WEBSEARCH_MCP_UI_PORT set it also answers HTTP, in the same
|
|
135
|
+
* process. A port that cannot be bound is reported and the MCP side carries on: an MCP client must
|
|
136
|
+
* never lose its tools because a page could not start.
|
|
137
|
+
*/
|
|
138
|
+
async function startEmbeddedUi(configFile) {
|
|
139
|
+
const decision = embeddedFromEnv();
|
|
140
|
+
if (!decision.target) {
|
|
141
|
+
if (decision.error)
|
|
142
|
+
log(`settings page stays off: WEBSEARCH_MCP_UI_PORT ${decision.error}`);
|
|
143
|
+
return undefined;
|
|
144
|
+
}
|
|
145
|
+
const { token } = resolveToken();
|
|
146
|
+
try {
|
|
147
|
+
const ui = await startUi({ configPath: configFile, host: decision.target.host, port: decision.target.port, ...(token === undefined ? {} : { token }), version: identity.version, log });
|
|
148
|
+
log(`settings page on ${decision.target.host}:${ui.port}, served by this process`);
|
|
149
|
+
for (const url of ui.urls)
|
|
150
|
+
log(`open ${url}`);
|
|
151
|
+
if (!token)
|
|
152
|
+
openWarning();
|
|
153
|
+
return { close: () => ui.close() };
|
|
154
|
+
}
|
|
155
|
+
catch (error) {
|
|
156
|
+
log(`settings page stays off: ${error instanceof Error ? error.message : String(error)}`);
|
|
157
|
+
return undefined;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
const wantsUi = flags.has('ui');
|
|
161
|
+
if (!wantsUi && flags.has('print-url')) {
|
|
162
|
+
const { token } = resolveToken();
|
|
163
|
+
const { host, port } = bindTarget();
|
|
164
|
+
for (const url of tokenUrls(host, port, token))
|
|
165
|
+
process.stdout.write(`${url}\n`);
|
|
166
|
+
if (!token)
|
|
167
|
+
openWarning();
|
|
168
|
+
else
|
|
169
|
+
log(`start the page with --ui --host ${host} --port ${port}`);
|
|
170
|
+
process.exit(0);
|
|
171
|
+
}
|
|
172
|
+
if (wantsUi) {
|
|
173
|
+
const { token } = resolveToken();
|
|
174
|
+
const { host, port } = bindTarget();
|
|
175
|
+
try {
|
|
176
|
+
const ui = await startUi({
|
|
177
|
+
configPath,
|
|
178
|
+
host,
|
|
179
|
+
port,
|
|
180
|
+
...(token === undefined ? {} : { token }),
|
|
181
|
+
version: identity.version,
|
|
182
|
+
log,
|
|
183
|
+
});
|
|
184
|
+
if (!token)
|
|
185
|
+
openWarning();
|
|
186
|
+
log(`settings page for ${configPath}`);
|
|
187
|
+
log(`listening on ${host}:${ui.port}`);
|
|
188
|
+
for (const url of ui.urls)
|
|
189
|
+
log(`open ${url}`);
|
|
190
|
+
if (token)
|
|
191
|
+
log('the token lives in this process only; set it with --token or WEBSEARCH_MCP_UI_TOKEN');
|
|
192
|
+
if (ui.urls.length > 1)
|
|
193
|
+
log('the bind is not loopback, so every address above serves the same page');
|
|
194
|
+
const stop = async () => { await ui.close(); process.exit(0); };
|
|
195
|
+
for (const signal of ['SIGINT', 'SIGTERM'])
|
|
196
|
+
process.on(signal, () => void stop());
|
|
197
|
+
}
|
|
198
|
+
catch (error) {
|
|
199
|
+
crash(error);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
else {
|
|
203
|
+
// stdio mode: the client owns the process, and the configuration is re-read when it changes on disk.
|
|
204
|
+
let config;
|
|
205
|
+
try {
|
|
206
|
+
config = await loadConfig({ configPath });
|
|
207
|
+
}
|
|
208
|
+
catch (error) {
|
|
209
|
+
crash(error);
|
|
210
|
+
throw error;
|
|
211
|
+
}
|
|
212
|
+
const source = watchSource(config, log);
|
|
213
|
+
const embedded = await startEmbeddedUi(config.configPath);
|
|
214
|
+
const tools = createTools(source, identity);
|
|
215
|
+
log(`ready with ${tools.length} tools; watching ${config.configPath}`);
|
|
216
|
+
let closing = false;
|
|
217
|
+
const shutdown = async () => {
|
|
218
|
+
if (closing)
|
|
219
|
+
return;
|
|
220
|
+
closing = true;
|
|
221
|
+
await handle?.close().catch(() => undefined);
|
|
222
|
+
await embedded?.close();
|
|
223
|
+
source.close();
|
|
224
|
+
process.exit(0);
|
|
225
|
+
};
|
|
226
|
+
for (const signal of ['SIGINT', 'SIGTERM'])
|
|
227
|
+
process.on(signal, () => void shutdown());
|
|
228
|
+
// The SDK owns stdin; its end is the client going away, which is this process's exit condition.
|
|
229
|
+
process.stdin.on('end', () => void shutdown());
|
|
230
|
+
process.stdin.on('close', () => void shutdown());
|
|
231
|
+
const handle = await serveTools(tools, identity, {
|
|
232
|
+
onerror: error => log(`mcp transport error: ${error.message}`),
|
|
233
|
+
});
|
|
234
|
+
log('mcp ready');
|
|
235
|
+
await new Promise(resolve => {
|
|
236
|
+
process.stdin.once('end', resolve);
|
|
237
|
+
process.stdin.once('close', resolve);
|
|
238
|
+
});
|
|
56
239
|
}
|
|
57
|
-
const lines = createInterface({ input: process.stdin, crlfDelay: Infinity });
|
|
58
|
-
for await (const line of lines)
|
|
59
|
-
await protocol.handle(line, abort.signal);
|
package/dist/sdk.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { McpServer } from '@modelcontextprotocol/server';
|
|
2
|
+
import { type StdioServerHandle } from '@modelcontextprotocol/server/stdio';
|
|
3
|
+
import type { ToolDefinition } from './tools.js';
|
|
4
|
+
export interface ServerIdentity {
|
|
5
|
+
name: string;
|
|
6
|
+
version: string;
|
|
7
|
+
projectUrl: string;
|
|
8
|
+
}
|
|
9
|
+
export interface ServeOptions {
|
|
10
|
+
onerror?: (error: Error) => void;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* One `McpServer` per era instance. The official SDK owns the wire protocol — the handshake, the
|
|
14
|
+
* stateless 2026-07-28 era, `server/discover`, validation and content framing — so a protocol
|
|
15
|
+
* revision reaches this package as a dependency bump instead of a rewrite of a hand-rolled loop.
|
|
16
|
+
*/
|
|
17
|
+
export declare function createServer(tools: readonly ToolDefinition[], identity: ServerIdentity): McpServer;
|
|
18
|
+
/** Serves stdio, negotiating the era per connection: modern 2026-07-28, or the 2025 handshake. */
|
|
19
|
+
export declare function serveTools(tools: readonly ToolDefinition[], identity: ServerIdentity, options?: ServeOptions): Promise<StdioServerHandle>;
|
|
20
|
+
/** Text rendering for clients that only read content[].text. */
|
|
21
|
+
export declare function render(value: unknown): string;
|
package/dist/sdk.js
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { fromJsonSchema, McpServer, } from '@modelcontextprotocol/server';
|
|
2
|
+
import { serveStdio } from '@modelcontextprotocol/server/stdio';
|
|
3
|
+
const INSTRUCTIONS = 'Multi-backend web search. Call list_backends first to see which backends are enabled, then web_search with an explicit strategy. read_thread opens a Reddit discussion.';
|
|
4
|
+
/**
|
|
5
|
+
* The tool surface is read-only: every call returns remote pages and never writes anywhere the
|
|
6
|
+
* caller owns. That is honest for a client that gates tools on annotations, and it is the same answer
|
|
7
|
+
* for both protocol eras the SDK serves.
|
|
8
|
+
*/
|
|
9
|
+
const ANNOTATIONS = {
|
|
10
|
+
web_search: { readOnlyHint: true, openWorldHint: true },
|
|
11
|
+
list_backends: { readOnlyHint: true, openWorldHint: false },
|
|
12
|
+
read_thread: { readOnlyHint: true, openWorldHint: true },
|
|
13
|
+
xiaohongshu_note: { readOnlyHint: true, openWorldHint: true },
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* One `McpServer` per era instance. The official SDK owns the wire protocol — the handshake, the
|
|
17
|
+
* stateless 2026-07-28 era, `server/discover`, validation and content framing — so a protocol
|
|
18
|
+
* revision reaches this package as a dependency bump instead of a rewrite of a hand-rolled loop.
|
|
19
|
+
*/
|
|
20
|
+
export function createServer(tools, identity) {
|
|
21
|
+
const server = new McpServer({ name: identity.name, version: identity.version }, { instructions: INSTRUCTIONS });
|
|
22
|
+
for (const tool of tools) {
|
|
23
|
+
const annotations = ANNOTATIONS[tool.name];
|
|
24
|
+
server.registerTool(tool.name, {
|
|
25
|
+
description: tool.description,
|
|
26
|
+
inputSchema: fromJsonSchema(tool.inputSchema),
|
|
27
|
+
...(annotations ? { annotations } : {}),
|
|
28
|
+
}, async (args, context) => {
|
|
29
|
+
try {
|
|
30
|
+
const value = await tool.call((args ?? {}), context.mcpReq.signal);
|
|
31
|
+
return resultOf(value);
|
|
32
|
+
}
|
|
33
|
+
catch (error) {
|
|
34
|
+
// A tool failure belongs inside the result, where the caller can quote it.
|
|
35
|
+
return { content: [{ type: 'text', text: error instanceof Error ? error.message : String(error) }], isError: true };
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
return server;
|
|
40
|
+
}
|
|
41
|
+
/** Serves stdio, negotiating the era per connection: modern 2026-07-28, or the 2025 handshake. */
|
|
42
|
+
export async function serveTools(tools, identity, options = {}) {
|
|
43
|
+
return serveStdio(() => createServer(tools, identity), options);
|
|
44
|
+
}
|
|
45
|
+
/** An MCP result is one text block plus one image block per picture that arrived. */
|
|
46
|
+
function resultOf(value) {
|
|
47
|
+
const content = [{ type: 'text', text: render(value) }];
|
|
48
|
+
const images = value?.images;
|
|
49
|
+
if (Array.isArray(images)) {
|
|
50
|
+
for (const image of images) {
|
|
51
|
+
if (typeof image?.data === 'string' && typeof image.mimeType === 'string' && image.mimeType !== '') {
|
|
52
|
+
content.push({ type: 'image', data: image.data, mimeType: image.mimeType });
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return { content, structuredContent: structuredCopy(value) };
|
|
57
|
+
}
|
|
58
|
+
/** The same value with payloads replaced by their size, for structuredContent. */
|
|
59
|
+
function structuredCopy(value) {
|
|
60
|
+
const images = value?.images;
|
|
61
|
+
if (!Array.isArray(images))
|
|
62
|
+
return value;
|
|
63
|
+
return {
|
|
64
|
+
...value,
|
|
65
|
+
images: images.map(image => {
|
|
66
|
+
const { data, ...rest } = image;
|
|
67
|
+
return typeof data === 'string' ? { ...rest, inline: true } : rest;
|
|
68
|
+
}),
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
/** Text rendering for clients that only read content[].text. */
|
|
72
|
+
export function render(value) {
|
|
73
|
+
if (value && typeof value === 'object') {
|
|
74
|
+
const record = value;
|
|
75
|
+
if (typeof record.text === 'string')
|
|
76
|
+
return record.text;
|
|
77
|
+
if (Array.isArray(record.sources)) {
|
|
78
|
+
const lines = [];
|
|
79
|
+
if (typeof record.report === 'string' && record.report !== '')
|
|
80
|
+
lines.push(record.report);
|
|
81
|
+
for (const source of record.sources) {
|
|
82
|
+
lines.push(`- ${source.title ?? source.url ?? ''} <${source.url ?? ''}>`);
|
|
83
|
+
}
|
|
84
|
+
return lines.join('\n') || 'No sources returned.';
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return JSON.stringify(value, null, 2);
|
|
88
|
+
}
|
package/dist/tools.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { SearchEngine, fetchRedditThread, fetchXhsComments, fetchXhsNote, fetchXThread } from '@nite07/search-core';
|
|
2
2
|
import type { ServerConfig } from './config.js';
|
|
3
|
+
import { type ConfigSource } from './live.js';
|
|
3
4
|
export interface ServerIdentity {
|
|
4
5
|
name: string;
|
|
5
6
|
version: string;
|
|
@@ -21,4 +22,4 @@ export interface NoteReaders {
|
|
|
21
22
|
note: typeof fetchXhsNote;
|
|
22
23
|
comments: typeof fetchXhsComments;
|
|
23
24
|
}
|
|
24
|
-
export declare function createTools(config: ServerConfig, identity: ServerIdentity, engine?: SearchEngine, readers?: ThreadReaders, notes?: NoteReaders): ToolDefinition[];
|
|
25
|
+
export declare function createTools(config: ServerConfig | ConfigSource, identity: ServerIdentity, engine?: SearchEngine, readers?: ThreadReaders, notes?: NoteReaders): ToolDefinition[];
|
package/dist/tools.js
CHANGED
|
@@ -1,15 +1,26 @@
|
|
|
1
1
|
import { SearchEngine, backendCredentialRef, browserCredentialRef, fetchRedditThread, fetchXhsComments, fetchXhsNote, fetchXThread, formatXhsNote, parseXCredentials, renderXhsNote, setUserAgent, } from '@nite07/search-core';
|
|
2
2
|
import { credentialResolver, describeBackends, enabledBackendIds } from './config.js';
|
|
3
|
+
import { asSource } from './live.js';
|
|
3
4
|
import { fetchImages } from './images.js';
|
|
4
5
|
const bool = (value) => (typeof value === 'boolean' ? value : undefined);
|
|
5
6
|
const int = (value) => (typeof value === 'number' && Number.isInteger(value) ? value : undefined);
|
|
6
7
|
const strings = (value) => Array.isArray(value) ? value.filter((item) => typeof item === 'string' && item.trim() !== '') : undefined;
|
|
7
8
|
export function createTools(config, identity, engine, readers = { reddit: fetchRedditThread, x: fetchXThread }, notes = { note: fetchXhsNote, comments: fetchXhsComments }) {
|
|
8
9
|
setUserAgent(`${identity.name}/${identity.version} (+${identity.projectUrl})`);
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
10
|
+
// Read through the source on every call: a configuration saved by the settings page has to reach a
|
|
11
|
+
// server that is already running, without a restart and without the engine keeping stale settings.
|
|
12
|
+
const configSource = asSource(config);
|
|
13
|
+
let cached;
|
|
14
|
+
const engineFor = (current) => {
|
|
15
|
+
if (engine)
|
|
16
|
+
return engine;
|
|
17
|
+
const revision = configSource.revision();
|
|
18
|
+
if (cached?.revision === revision)
|
|
19
|
+
return cached.engine;
|
|
20
|
+
const created = new SearchEngine(current.search, reference => credentialResolver(current)(reference));
|
|
21
|
+
cached = { revision, engine: created };
|
|
22
|
+
return created;
|
|
23
|
+
};
|
|
13
24
|
const searchTool = {
|
|
14
25
|
name: 'web_search',
|
|
15
26
|
description: 'Search the web through the configured backends and return citeable sources. The strategy is explicit: pick parallel or single mode, choose which enabled backends to use, and how much of each source to return. Failures are named instead of being hidden behind an empty result, and the response reports every request that failed. Nothing falls back to another backend, mode or credential.',
|
|
@@ -28,6 +39,8 @@ export function createTools(config, identity, engine, readers = { reddit: fetchR
|
|
|
28
39
|
required: ['query'],
|
|
29
40
|
},
|
|
30
41
|
async call(args, signal) {
|
|
42
|
+
const config = configSource.get();
|
|
43
|
+
const search = engineFor(config);
|
|
31
44
|
const query = String(args.query ?? '').trim();
|
|
32
45
|
if (!query)
|
|
33
46
|
throw new Error('web_search needs a non-empty query.');
|
|
@@ -64,6 +77,7 @@ export function createTools(config, identity, engine, readers = { reddit: fetchR
|
|
|
64
77
|
},
|
|
65
78
|
},
|
|
66
79
|
async call(args, signal) {
|
|
80
|
+
const config = configSource.get();
|
|
67
81
|
const source = typeof args.source === 'string' ? args.source : 'reddit';
|
|
68
82
|
const id = String(args.postId ?? args.url ?? '').trim();
|
|
69
83
|
if (!id)
|
|
@@ -117,6 +131,7 @@ export function createTools(config, identity, engine, readers = { reddit: fetchR
|
|
|
117
131
|
required: [],
|
|
118
132
|
},
|
|
119
133
|
async call(args, signal) {
|
|
134
|
+
const config = configSource.get();
|
|
120
135
|
const target = {
|
|
121
136
|
...(typeof args.url === 'string' && args.url.trim() ? { url: args.url.trim() } : {}),
|
|
122
137
|
...(typeof args.id === 'string' && args.id.trim() ? { id: args.id.trim() } : {}),
|
|
@@ -143,6 +158,7 @@ export function createTools(config, identity, engine, readers = { reddit: fetchR
|
|
|
143
158
|
description: 'List every backend this server knows about with its access modes, cost tier, whether it is enabled and whether a credential is present. Use it to decide which backends a search should address; it never enables anything.',
|
|
144
159
|
inputSchema: { type: 'object', properties: {} },
|
|
145
160
|
async call() {
|
|
161
|
+
const config = configSource.get();
|
|
146
162
|
return { configPath: config.configPath, enabled: enabledBackendIds(config), backends: describeBackends(config) };
|
|
147
163
|
},
|
|
148
164
|
};
|