@nite07/websearch-mcp 0.1.4 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +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 +4 -3
- package/dist/protocol.d.ts +0 -19
- package/dist/protocol.js +0 -125
package/dist/ui/state.js
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
import { chmod, open, readFile, readdir, rename, stat, unlink } from 'node:fs/promises';
|
|
2
|
+
import { realpathSync } from 'node:fs';
|
|
3
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
4
|
+
import { homedir } from 'node:os';
|
|
5
|
+
import { basename, dirname, join } from 'node:path';
|
|
6
|
+
import { backendCredentialRef, browserCredentialRef, catalog, defaultConfig, parseConfig, validateConfig, } from '@nite07/search-core';
|
|
7
|
+
export class SettingsError extends Error {
|
|
8
|
+
issues;
|
|
9
|
+
status;
|
|
10
|
+
constructor(message, issues = [], status = 400) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.issues = issues;
|
|
13
|
+
this.status = status;
|
|
14
|
+
this.name = 'SettingsError';
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export const MAX_CREDENTIAL_LENGTH = 16384;
|
|
18
|
+
/** Inside a container, loopback is the container itself, so a companion file names the host instead. */
|
|
19
|
+
export const CONTAINER_HOST = 'host.containers.internal';
|
|
20
|
+
const BACKUP_LIMIT = 5;
|
|
21
|
+
const hash = (text) => createHash('sha256').update(text).digest('hex').slice(0, 16);
|
|
22
|
+
/** The same settings for a client that runs in a container: loopback there means the container. */
|
|
23
|
+
export const companionPath = (path) => `${path.replace(/\.json$/i, '')}.container.json`;
|
|
24
|
+
function rewriteEndpoint(endpoint) {
|
|
25
|
+
if (!endpoint)
|
|
26
|
+
return endpoint;
|
|
27
|
+
try {
|
|
28
|
+
const url = new URL(endpoint);
|
|
29
|
+
const loopback = ['127.0.0.1', 'localhost', '[::1]', '::1'];
|
|
30
|
+
if (!loopback.includes(url.hostname))
|
|
31
|
+
return endpoint;
|
|
32
|
+
url.hostname = CONTAINER_HOST;
|
|
33
|
+
return url.toString();
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return endpoint;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
/** The session file is read by path, and inside the container the home directory is a read-only mount. */
|
|
40
|
+
const CONTAINER_HOME = '/host/home';
|
|
41
|
+
const CORE_BROWSER_STATE = join('.config', 'dsh-search', 'browser', 'state.json');
|
|
42
|
+
function containerStatePath(value, home) {
|
|
43
|
+
const written = value || join(home, CORE_BROWSER_STATE);
|
|
44
|
+
let resolved = written;
|
|
45
|
+
try {
|
|
46
|
+
// The path is usually a symlink into the browser container's data volume; the container mount
|
|
47
|
+
// sees the real directory, not the symlink, so the resolved path is what has to be mapped.
|
|
48
|
+
resolved = realpathSync(written);
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
// Not there yet: map what was written.
|
|
52
|
+
}
|
|
53
|
+
return resolved.startsWith(`${home}/`) ? `${CONTAINER_HOME}/${resolved.slice(home.length + 1)}` : resolved;
|
|
54
|
+
}
|
|
55
|
+
export function containerVariant(search, home = homedir()) {
|
|
56
|
+
const copy = structuredClone(search);
|
|
57
|
+
copy.browser = {
|
|
58
|
+
...copy.browser,
|
|
59
|
+
endpoint: rewriteEndpoint(copy.browser.endpoint),
|
|
60
|
+
statePath: containerStatePath(copy.browser.statePath, home),
|
|
61
|
+
};
|
|
62
|
+
for (const backend of Object.values(copy.backends)) {
|
|
63
|
+
backend.endpoint = rewriteEndpoint(backend.endpoint);
|
|
64
|
+
}
|
|
65
|
+
return copy;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* A companion file is written only when it already exists: creating one for every install would put a
|
|
69
|
+
* second copy of the credentials somewhere the operator never asked for.
|
|
70
|
+
*/
|
|
71
|
+
async function writeCompanion(path, body) {
|
|
72
|
+
const target = companionPath(path);
|
|
73
|
+
const present = await readText(target);
|
|
74
|
+
if (!present)
|
|
75
|
+
return undefined;
|
|
76
|
+
const variant = { ...body, search: containerVariant(body.search) };
|
|
77
|
+
await writeAtomic(target, `${JSON.stringify(variant, null, 2)}\n`);
|
|
78
|
+
return target;
|
|
79
|
+
}
|
|
80
|
+
async function readText(path) {
|
|
81
|
+
try {
|
|
82
|
+
const text = await readFile(path, 'utf8');
|
|
83
|
+
return { text, revision: hash(text) };
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
const code = error.code;
|
|
87
|
+
if (code === 'ENOENT')
|
|
88
|
+
return undefined;
|
|
89
|
+
throw error;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
function parseRaw(text) {
|
|
93
|
+
let body;
|
|
94
|
+
try {
|
|
95
|
+
body = JSON.parse(text);
|
|
96
|
+
}
|
|
97
|
+
catch (error) {
|
|
98
|
+
throw new SettingsError('The configuration file is not valid JSON.', [{ path: '', message: String(error) }]);
|
|
99
|
+
}
|
|
100
|
+
if (!body || typeof body !== 'object' || Array.isArray(body))
|
|
101
|
+
throw new SettingsError('The configuration file must hold a JSON object.');
|
|
102
|
+
const record = body;
|
|
103
|
+
const credentials = {};
|
|
104
|
+
for (const [id, value] of Object.entries((record.credentials ?? {}))) {
|
|
105
|
+
if (typeof value === 'string' && value.trim() !== '')
|
|
106
|
+
credentials[id] = value;
|
|
107
|
+
}
|
|
108
|
+
const { search, credentials: _credentials, compactByDefault, ...rest } = record;
|
|
109
|
+
return { search: search ?? {}, credentials, compactByDefault: compactByDefault === true, rest };
|
|
110
|
+
}
|
|
111
|
+
/** Atomic and private: a half-written configuration must never be readable by the next process. */
|
|
112
|
+
async function writeAtomic(path, text) {
|
|
113
|
+
const temporary = join(dirname(path), `.${basename(path)}.tmp-${process.pid}-${randomBytes(6).toString('hex')}`);
|
|
114
|
+
const handle = await open(temporary, 'w', 0o600);
|
|
115
|
+
try {
|
|
116
|
+
await handle.writeFile(text, 'utf8');
|
|
117
|
+
await handle.sync();
|
|
118
|
+
}
|
|
119
|
+
finally {
|
|
120
|
+
await handle.close();
|
|
121
|
+
}
|
|
122
|
+
try {
|
|
123
|
+
await rename(temporary, path);
|
|
124
|
+
}
|
|
125
|
+
catch (error) {
|
|
126
|
+
await unlink(temporary).catch(() => undefined);
|
|
127
|
+
throw error;
|
|
128
|
+
}
|
|
129
|
+
await chmod(path, 0o600).catch(() => undefined);
|
|
130
|
+
}
|
|
131
|
+
async function backup(path, text) {
|
|
132
|
+
// Local time and milliseconds: a backup is something a person reads while looking for "the one
|
|
133
|
+
// from ten minutes ago", and two saves inside the same second must not overwrite each other.
|
|
134
|
+
const now = new Date();
|
|
135
|
+
const pad = (value) => String(value).padStart(2, '0');
|
|
136
|
+
const stamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}-${String(now.getMilliseconds()).padStart(3, '0')}`;
|
|
137
|
+
const target = `${path}.bak-${stamp}`;
|
|
138
|
+
await writeAtomic(target, text);
|
|
139
|
+
// Sorted by mtime, not by name: a name carries the writer's local time, and the same directory may
|
|
140
|
+
// be written by a host process and by a container whose clock is UTC.
|
|
141
|
+
const directory = dirname(path);
|
|
142
|
+
const prefix = `${basename(path)}.bak-`;
|
|
143
|
+
const names = (await readdir(directory).catch(() => [])).filter(name => name.startsWith(prefix));
|
|
144
|
+
const entries = await Promise.all(names.map(async (name) => {
|
|
145
|
+
const info = await stat(join(directory, name)).catch(() => undefined);
|
|
146
|
+
return { name, at: info?.mtimeMs ?? 0 };
|
|
147
|
+
}));
|
|
148
|
+
const stale = entries.sort((a, b) => b.at - a.at).slice(BACKUP_LIMIT).map(entry => entry.name);
|
|
149
|
+
await Promise.all(stale.map(name => unlink(join(directory, name)).catch(() => undefined)));
|
|
150
|
+
return target;
|
|
151
|
+
}
|
|
152
|
+
function credentialState(id, ref, mode, file, env) {
|
|
153
|
+
const fromEnv = typeof env[ref] === 'string' && env[ref] !== '';
|
|
154
|
+
const fromFile = typeof file[id] === 'string' && file[id] !== '';
|
|
155
|
+
return {
|
|
156
|
+
id,
|
|
157
|
+
ref,
|
|
158
|
+
mode,
|
|
159
|
+
source: fromEnv ? 'env' : fromFile ? 'file' : 'none',
|
|
160
|
+
length: fromFile ? file[id].length : 0,
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
export async function snapshot(path, env = process.env) {
|
|
164
|
+
const file = await readText(path);
|
|
165
|
+
const defaults = defaultConfig();
|
|
166
|
+
let raw;
|
|
167
|
+
let loadError;
|
|
168
|
+
if (file) {
|
|
169
|
+
try {
|
|
170
|
+
raw = parseRaw(file.text);
|
|
171
|
+
}
|
|
172
|
+
catch (error) {
|
|
173
|
+
loadError = error instanceof Error ? error.message : String(error);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
let config = defaults;
|
|
177
|
+
if (raw) {
|
|
178
|
+
try {
|
|
179
|
+
config = parseConfig(raw.search);
|
|
180
|
+
}
|
|
181
|
+
catch (error) {
|
|
182
|
+
loadError = error instanceof Error ? error.message : String(error);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
const stored = raw?.credentials ?? {};
|
|
186
|
+
return {
|
|
187
|
+
configPath: path,
|
|
188
|
+
revision: file?.revision ?? 'missing',
|
|
189
|
+
config,
|
|
190
|
+
defaults,
|
|
191
|
+
catalog,
|
|
192
|
+
credentials: catalog.map(item => credentialState(item.id, backendCredentialRef(item.id), config.backends[item.id]?.mode ?? null, stored, env)),
|
|
193
|
+
browser: credentialState('browser', browserCredentialRef(), null, stored, env),
|
|
194
|
+
compactByDefault: raw?.compactByDefault ?? false,
|
|
195
|
+
companion: { path: companionPath(path), active: Boolean(await readText(companionPath(path))) },
|
|
196
|
+
...(loadError ? { loadError } : {}),
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Validates first and writes second: a rejected save leaves the file byte-identical, which is what
|
|
201
|
+
* lets the page show the issues without having damaged a working configuration.
|
|
202
|
+
*/
|
|
203
|
+
export async function saveConfig(path, input) {
|
|
204
|
+
const issues = validateConfig(input.config);
|
|
205
|
+
if (issues.length)
|
|
206
|
+
throw new SettingsError('The configuration did not validate.', issues);
|
|
207
|
+
const search = parseConfig(input.config);
|
|
208
|
+
const existing = await readText(path);
|
|
209
|
+
if (input.expectedRevision !== undefined && input.expectedRevision !== (existing?.revision ?? 'missing')) {
|
|
210
|
+
throw new SettingsError('The file changed since the page loaded it; reload before saving.', [], 409);
|
|
211
|
+
}
|
|
212
|
+
const raw = existing ? parseRaw(existing.text) : { search: {}, credentials: {}, compactByDefault: false, rest: {} };
|
|
213
|
+
const body = {
|
|
214
|
+
...raw.rest,
|
|
215
|
+
search,
|
|
216
|
+
credentials: raw.credentials,
|
|
217
|
+
compactByDefault: input.compactByDefault ?? raw.compactByDefault,
|
|
218
|
+
};
|
|
219
|
+
const text = `${JSON.stringify(body, null, 2)}\n`;
|
|
220
|
+
const saved = existing ? await backup(path, existing.text) : undefined;
|
|
221
|
+
await writeAtomic(path, text);
|
|
222
|
+
await writeCompanion(path, body);
|
|
223
|
+
return { revision: hash(text), ...(saved ? { backup: saved } : {}) };
|
|
224
|
+
}
|
|
225
|
+
export async function saveCredential(path, input) {
|
|
226
|
+
const existing = await readText(path);
|
|
227
|
+
const raw = existing ? parseRaw(existing.text) : { search: {}, credentials: {}, compactByDefault: false, rest: {} };
|
|
228
|
+
const credentials = { ...raw.credentials };
|
|
229
|
+
let key;
|
|
230
|
+
if (input.scope === 'browser') {
|
|
231
|
+
key = 'browser';
|
|
232
|
+
}
|
|
233
|
+
else {
|
|
234
|
+
const id = String(input.id ?? '');
|
|
235
|
+
if (!catalog.some(item => item.id === id))
|
|
236
|
+
throw new SettingsError(`Unknown backend id: ${id || '(none)'}.`);
|
|
237
|
+
key = id;
|
|
238
|
+
}
|
|
239
|
+
if (input.remove === true)
|
|
240
|
+
delete credentials[key];
|
|
241
|
+
else {
|
|
242
|
+
const value = typeof input.value === 'string' ? input.value.trim() : '';
|
|
243
|
+
if (!value)
|
|
244
|
+
throw new SettingsError('A credential cannot be empty.');
|
|
245
|
+
if (value.length > MAX_CREDENTIAL_LENGTH)
|
|
246
|
+
throw new SettingsError(`A credential is limited to ${MAX_CREDENTIAL_LENGTH} characters.`);
|
|
247
|
+
credentials[key] = value;
|
|
248
|
+
}
|
|
249
|
+
const body = { ...raw.rest, search: raw.search, credentials, compactByDefault: raw.compactByDefault };
|
|
250
|
+
const text = `${JSON.stringify(body, null, 2)}\n`;
|
|
251
|
+
await writeAtomic(path, text);
|
|
252
|
+
await writeCompanion(path, body);
|
|
253
|
+
const after = await snapshot(path, {});
|
|
254
|
+
const state = key === 'browser' ? after.browser : after.credentials.find(item => item.id === key);
|
|
255
|
+
return { revision: hash(text), state };
|
|
256
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** Where the token came from, so the log can say what is protecting (or not protecting) the page. */
|
|
2
|
+
export type TokenSource = 'flag' | 'env' | 'none';
|
|
3
|
+
export interface TokenDecision {
|
|
4
|
+
/** Undefined means the page runs without authentication, as asked. */
|
|
5
|
+
token?: string;
|
|
6
|
+
source: TokenSource;
|
|
7
|
+
note: string;
|
|
8
|
+
}
|
|
9
|
+
export interface TokenInput {
|
|
10
|
+
/** --token <value> */
|
|
11
|
+
flag?: string;
|
|
12
|
+
/** --no-token */
|
|
13
|
+
open?: boolean;
|
|
14
|
+
env?: NodeJS.ProcessEnv;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* The token comes from the command line or the environment; this process never writes one. A page that
|
|
18
|
+
* can rewrite credentials needs a secret, but a secret on disk is another copy to lose and another file
|
|
19
|
+
* to mount: an operator already has to place the credentials in the configuration, so the token is
|
|
20
|
+
* their call too. Unset means the page is open, which the log says plainly.
|
|
21
|
+
*/
|
|
22
|
+
export declare function decideToken(input: TokenInput): TokenDecision;
|
|
23
|
+
export declare const tokenIsShort: (token: string) => boolean;
|
package/dist/ui/token.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
const SHORT_TOKEN = 16;
|
|
2
|
+
const clean = (value) => {
|
|
3
|
+
const trimmed = value?.trim();
|
|
4
|
+
return trimmed ? trimmed : undefined;
|
|
5
|
+
};
|
|
6
|
+
/**
|
|
7
|
+
* The token comes from the command line or the environment; this process never writes one. A page that
|
|
8
|
+
* can rewrite credentials needs a secret, but a secret on disk is another copy to lose and another file
|
|
9
|
+
* to mount: an operator already has to place the credentials in the configuration, so the token is
|
|
10
|
+
* their call too. Unset means the page is open, which the log says plainly.
|
|
11
|
+
*/
|
|
12
|
+
export function decideToken(input) {
|
|
13
|
+
if (input.open === true)
|
|
14
|
+
return { source: 'none', note: 'authentication disabled by --no-token' };
|
|
15
|
+
const flag = clean(input.flag);
|
|
16
|
+
if (flag)
|
|
17
|
+
return { token: flag, source: 'flag', note: 'token from --token' };
|
|
18
|
+
const env = clean((input.env ?? process.env).WEBSEARCH_MCP_UI_TOKEN);
|
|
19
|
+
if (env)
|
|
20
|
+
return { token: env, source: 'env', note: 'token from WEBSEARCH_MCP_UI_TOKEN' };
|
|
21
|
+
return { source: 'none', note: 'no token in --token or WEBSEARCH_MCP_UI_TOKEN, so the page is open' };
|
|
22
|
+
}
|
|
23
|
+
export const tokenIsShort = (token) => token.length < SHORT_TOKEN;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nite07/websearch-mcp",
|
|
3
|
-
"version": "0.1
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"description": "MCP server for multi-backend web search plus Reddit and X thread reading, built on @nite07/search-core.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "nite07",
|
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
"config.example.json"
|
|
33
33
|
],
|
|
34
34
|
"scripts": {
|
|
35
|
-
"build": "rm -rf dist && tsc -p tsconfig.build.json",
|
|
35
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json && node scripts/copy-assets.mjs",
|
|
36
36
|
"typecheck": "tsc --noEmit",
|
|
37
37
|
"test": "node --import tsx --test test/*.test.ts",
|
|
38
38
|
"check": "npm run typecheck && npm run test && npm run build",
|
|
@@ -42,7 +42,8 @@
|
|
|
42
42
|
"node": ">=22"
|
|
43
43
|
},
|
|
44
44
|
"dependencies": {
|
|
45
|
-
"@
|
|
45
|
+
"@modelcontextprotocol/server": "^2.4.0",
|
|
46
|
+
"@nite07/search-core": "0.1.8"
|
|
46
47
|
},
|
|
47
48
|
"devDependencies": {
|
|
48
49
|
"@types/node": "^22.10.2",
|
package/dist/protocol.d.ts
DELETED
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
import type { ToolDefinition } from './tools.js';
|
|
2
|
-
/**
|
|
3
|
-
* Minimal MCP server over stdio: newline-delimited JSON-RPC 2.0, one message per line.
|
|
4
|
-
* Only what this server needs is implemented — initialize, ping, tools/list and tools/call —
|
|
5
|
-
* and unknown methods answer with a JSON-RPC error instead of silence.
|
|
6
|
-
*/
|
|
7
|
-
export declare const PROTOCOL_VERSION = "2025-06-18";
|
|
8
|
-
export interface ServerInfo {
|
|
9
|
-
name: string;
|
|
10
|
-
version: string;
|
|
11
|
-
}
|
|
12
|
-
export interface Writer {
|
|
13
|
-
write(chunk: string): boolean;
|
|
14
|
-
}
|
|
15
|
-
export declare function createProtocol(tools: ToolDefinition[], info: ServerInfo, writer: Writer): {
|
|
16
|
-
handle(line: string, signal: AbortSignal): Promise<void>;
|
|
17
|
-
};
|
|
18
|
-
/** Text rendering for clients that only read content[].text. */
|
|
19
|
-
export declare function render(value: unknown): string;
|
package/dist/protocol.js
DELETED
|
@@ -1,125 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Minimal MCP server over stdio: newline-delimited JSON-RPC 2.0, one message per line.
|
|
3
|
-
* Only what this server needs is implemented — initialize, ping, tools/list and tools/call —
|
|
4
|
-
* and unknown methods answer with a JSON-RPC error instead of silence.
|
|
5
|
-
*/
|
|
6
|
-
export const PROTOCOL_VERSION = '2025-06-18';
|
|
7
|
-
const SUPPORTED = new Set(['2024-11-05', '2025-03-26', '2025-06-18']);
|
|
8
|
-
export function createProtocol(tools, info, writer) {
|
|
9
|
-
const send = (message) => { writer.write(`${JSON.stringify(message)}\n`); };
|
|
10
|
-
const result = (id, value) => send({ jsonrpc: '2.0', id, result: value });
|
|
11
|
-
const fail = (id, code, message, data) => send({ jsonrpc: '2.0', id, error: { code, message, ...(data === undefined ? {} : { data }) } });
|
|
12
|
-
async function dispatch(request, signal) {
|
|
13
|
-
const id = request.id ?? null;
|
|
14
|
-
const isNotification = request.id === undefined;
|
|
15
|
-
switch (request.method) {
|
|
16
|
-
case 'initialize': {
|
|
17
|
-
const asked = request.params?.protocolVersion;
|
|
18
|
-
const version = typeof asked === 'string' && SUPPORTED.has(asked) ? asked : PROTOCOL_VERSION;
|
|
19
|
-
result(id, {
|
|
20
|
-
protocolVersion: version,
|
|
21
|
-
capabilities: { tools: { listChanged: false } },
|
|
22
|
-
serverInfo: { name: info.name, version: info.version },
|
|
23
|
-
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.',
|
|
24
|
-
});
|
|
25
|
-
return;
|
|
26
|
-
}
|
|
27
|
-
case 'ping':
|
|
28
|
-
result(id, {});
|
|
29
|
-
return;
|
|
30
|
-
case 'tools/list':
|
|
31
|
-
result(id, {
|
|
32
|
-
tools: tools.map(tool => ({ name: tool.name, description: tool.description, inputSchema: tool.inputSchema })),
|
|
33
|
-
});
|
|
34
|
-
return;
|
|
35
|
-
case 'tools/call': {
|
|
36
|
-
const name = String(request.params?.name ?? '');
|
|
37
|
-
const args = (request.params?.arguments ?? {});
|
|
38
|
-
const tool = tools.find(candidate => candidate.name === name);
|
|
39
|
-
if (!tool) {
|
|
40
|
-
fail(id, -32602, `Unknown tool: ${name}`, { available: tools.map(item => item.name) });
|
|
41
|
-
return;
|
|
42
|
-
}
|
|
43
|
-
try {
|
|
44
|
-
const value = await tool.call(args, signal);
|
|
45
|
-
result(id, { content: contentBlocks(value), structuredContent: structuredCopy(value), isError: false });
|
|
46
|
-
}
|
|
47
|
-
catch (error) {
|
|
48
|
-
// A tool failure is reported inside the result, with the message the caller needs.
|
|
49
|
-
result(id, { content: [{ type: 'text', text: error instanceof Error ? error.message : String(error) }], isError: true });
|
|
50
|
-
}
|
|
51
|
-
return;
|
|
52
|
-
}
|
|
53
|
-
default:
|
|
54
|
-
if (!isNotification)
|
|
55
|
-
fail(id, -32601, `Method not found: ${request.method}`);
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
return {
|
|
59
|
-
async handle(line, signal) {
|
|
60
|
-
const trimmed = line.trim();
|
|
61
|
-
if (trimmed === '')
|
|
62
|
-
return;
|
|
63
|
-
let request;
|
|
64
|
-
try {
|
|
65
|
-
request = JSON.parse(trimmed);
|
|
66
|
-
}
|
|
67
|
-
catch {
|
|
68
|
-
fail(null, -32700, 'Parse error: the line is not JSON.');
|
|
69
|
-
return;
|
|
70
|
-
}
|
|
71
|
-
if (!request || typeof request !== 'object' || typeof request.method !== 'string') {
|
|
72
|
-
fail(null, -32600, 'Invalid request.');
|
|
73
|
-
return;
|
|
74
|
-
}
|
|
75
|
-
await dispatch(request, signal);
|
|
76
|
-
},
|
|
77
|
-
};
|
|
78
|
-
}
|
|
79
|
-
/**
|
|
80
|
-
* An MCP result is one text block plus one image block per picture that arrived. Base64 never goes
|
|
81
|
-
* into structuredContent, which exists for machine-readable fields rather than payloads.
|
|
82
|
-
*/
|
|
83
|
-
function contentBlocks(value) {
|
|
84
|
-
const blocks = [{ type: 'text', text: render(value) }];
|
|
85
|
-
const images = value?.images;
|
|
86
|
-
if (Array.isArray(images)) {
|
|
87
|
-
for (const image of images) {
|
|
88
|
-
if (typeof image?.data === 'string' && typeof image.mimeType === 'string' && image.mimeType !== '') {
|
|
89
|
-
blocks.push({ type: 'image', data: image.data, mimeType: image.mimeType });
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
return blocks;
|
|
94
|
-
}
|
|
95
|
-
/** The same value with payloads replaced by their size, for structuredContent. */
|
|
96
|
-
function structuredCopy(value) {
|
|
97
|
-
const images = value?.images;
|
|
98
|
-
if (!Array.isArray(images))
|
|
99
|
-
return value;
|
|
100
|
-
return {
|
|
101
|
-
...value,
|
|
102
|
-
images: images.map(image => {
|
|
103
|
-
const { data, ...rest } = image;
|
|
104
|
-
return typeof data === 'string' ? { ...rest, inline: true } : rest;
|
|
105
|
-
}),
|
|
106
|
-
};
|
|
107
|
-
}
|
|
108
|
-
/** Text rendering for clients that only read content[].text. */
|
|
109
|
-
export function render(value) {
|
|
110
|
-
if (value && typeof value === 'object') {
|
|
111
|
-
const record = value;
|
|
112
|
-
if (typeof record.text === 'string')
|
|
113
|
-
return record.text;
|
|
114
|
-
if (Array.isArray(record.sources)) {
|
|
115
|
-
const lines = [];
|
|
116
|
-
if (typeof record.report === 'string' && record.report !== '')
|
|
117
|
-
lines.push(record.report);
|
|
118
|
-
for (const source of record.sources) {
|
|
119
|
-
lines.push(`- ${source.title ?? source.url ?? ''} <${source.url ?? ''}>`);
|
|
120
|
-
}
|
|
121
|
-
return lines.join('\n') || 'No sources returned.';
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
return JSON.stringify(value, null, 2);
|
|
125
|
-
}
|