@v1nvn/readability 0.44.0 → 0.45.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.
Files changed (71) hide show
  1. package/README.md +3 -3
  2. package/package.json +7 -9
  3. package/src/cli.ts +134 -0
  4. package/src/config.ts +42 -0
  5. package/src/dev.ts +77 -0
  6. package/src/errors.ts +19 -0
  7. package/src/handler.ts +8 -0
  8. package/src/host-sampling.ts +86 -0
  9. package/src/index.ts +27 -0
  10. package/src/logger.ts +3 -0
  11. package/src/output/format.ts +132 -0
  12. package/src/pipeline/cell-text.ts +56 -0
  13. package/src/pipeline/context.ts +88 -0
  14. package/src/pipeline/dom.ts +23 -0
  15. package/src/pipeline/footnotes.ts +181 -0
  16. package/src/pipeline/math.ts +130 -0
  17. package/src/pipeline/normalize.ts +594 -0
  18. package/src/pipeline/readability.ts +36 -0
  19. package/src/pipeline/resolver.ts +143 -0
  20. package/src/pipeline/sanitize.ts +42 -0
  21. package/src/pipeline/tables.ts +286 -0
  22. package/src/pipeline/turndown.ts +191 -0
  23. package/src/pipeline/urls.ts +13 -0
  24. package/src/policy/chunk.ts +482 -0
  25. package/src/policy/diagnostics.ts +96 -0
  26. package/src/policy/explain.ts +182 -0
  27. package/src/policy/fallback.ts +110 -0
  28. package/src/policy/gating.ts +106 -0
  29. package/src/policy/grid-detector.ts +313 -0
  30. package/src/policy/identifiers.ts +75 -0
  31. package/src/policy/images.ts +64 -0
  32. package/src/policy/list-detector.ts +308 -0
  33. package/src/policy/lost-signal.ts +69 -0
  34. package/src/policy/markdown.ts +76 -0
  35. package/src/policy/metadata.ts +312 -0
  36. package/src/policy/outline-chains.ts +215 -0
  37. package/src/policy/outline.ts +89 -0
  38. package/src/policy/pagination.ts +104 -0
  39. package/src/policy/presets.ts +142 -0
  40. package/src/policy/section.ts +127 -0
  41. package/src/policy/selector-lint.ts +186 -0
  42. package/src/policy/sibling-scan.ts +99 -0
  43. package/src/policy/text.ts +36 -0
  44. package/src/policy/truncate.ts +59 -0
  45. package/src/preset-cache.ts +221 -0
  46. package/src/resources.ts +317 -0
  47. package/src/sampling.ts +74 -0
  48. package/src/server.ts +85 -0
  49. package/src/tools/chunk_text.ts +65 -0
  50. package/src/tools/explain.ts +299 -0
  51. package/src/tools/extract.ts +368 -0
  52. package/src/tools/extract_grid.ts +90 -0
  53. package/src/tools/extract_links.ts +138 -0
  54. package/src/tools/extract_list.ts +97 -0
  55. package/src/tools/extract_metadata.ts +102 -0
  56. package/src/tools/extract_section.ts +84 -0
  57. package/src/tools/extract_tables.ts +101 -0
  58. package/src/tools/html-source.ts +40 -0
  59. package/src/tools/html_to_markdown.ts +180 -0
  60. package/src/tools/outline.ts +77 -0
  61. package/src/tools/output-schema.ts +715 -0
  62. package/src/tools/schemas.ts +442 -0
  63. package/src/tools/suggest-preset.ts +708 -0
  64. package/src/types/jsdom.d.ts +15 -0
  65. package/src/types/turndown-plugin-gfm.d.ts +11 -0
  66. package/dist/assets/cli-Dfjg7dOQ.js +0 -76
  67. package/dist/assets/cli-Dfjg7dOQ.js.map +0 -1
  68. package/dist/assets/extract-CdDp-KwX.js +0 -2880
  69. package/dist/assets/extract-CdDp-KwX.js.map +0 -1
  70. package/dist/index.js +0 -2267
  71. package/dist/index.js.map +0 -1
@@ -0,0 +1,59 @@
1
+ import { hardSplitLines, parseBlocks } from './markdown.ts';
2
+
3
+ export interface TruncateResult {
4
+ readonly text: string;
5
+ readonly truncated: boolean;
6
+ }
7
+
8
+ const TRUNCATION_MARKER = '\n\n…[truncated]';
9
+
10
+ // Cuts at a top-level block boundary. A fenced code block is a single mdast
11
+ // node, so a boundary cut never lands inside one — no open-fence rollback is
12
+ // needed. The kept span is sliced from the original string so the payload is a
13
+ // byte-for-byte prefix of the Turndown output.
14
+ export function truncateMarkdown(
15
+ markdown: string,
16
+ maxChars: number,
17
+ ): TruncateResult {
18
+ if (markdown.length <= maxChars) {
19
+ return { text: markdown, truncated: false };
20
+ }
21
+
22
+ const blocks = parseBlocks(markdown);
23
+ let start = -1;
24
+ let end = -1;
25
+ let truncated = false;
26
+ for (const block of blocks) {
27
+ const from = start === -1 ? block.start : start;
28
+ if (block.end - from > maxChars) {
29
+ // First non-code block alone overflows: take a line-aware prefix instead
30
+ // of dropping everything. A code block is never split — a half-open fence
31
+ // is unrecoverable — so an oversized first code block stays dropped.
32
+ if (start === -1 && block.kind !== 'code') {
33
+ const firstPiece =
34
+ hardSplitLines(markdown.slice(block.start, block.end), maxChars)[0] ??
35
+ '';
36
+ return {
37
+ text: firstPiece.replace(/\s+$/, '') + TRUNCATION_MARKER,
38
+ truncated: true,
39
+ };
40
+ }
41
+ truncated = true;
42
+ break;
43
+ }
44
+ if (start === -1) {
45
+ start = block.start;
46
+ }
47
+ end = block.end;
48
+ }
49
+
50
+ if (!truncated) {
51
+ return { text: markdown, truncated: false };
52
+ }
53
+
54
+ const kept = start === -1 ? '' : markdown.slice(start, end);
55
+ return {
56
+ text: kept.replace(/\s+$/, '') + TRUNCATION_MARKER,
57
+ truncated: true,
58
+ };
59
+ }
@@ -0,0 +1,221 @@
1
+ // Disk side of the preset store: one <site>.json file per preset, read into
2
+ // the in-memory store at boot. Local to the user's machine, ordinary files;
3
+ // the server never fetches and nothing expires by clock — staleness is
4
+ // detector-checked per page (policy/presets.ts), so eviction here is disk
5
+ // hygiene only.
6
+
7
+ import { describeError } from '@v1nvn/agentic-core';
8
+ import {
9
+ mkdirSync,
10
+ readdirSync,
11
+ readFileSync,
12
+ statSync,
13
+ unlinkSync,
14
+ writeFileSync,
15
+ } from 'node:fs';
16
+ import { homedir } from 'node:os';
17
+ import { join } from 'node:path';
18
+ import { z } from 'zod';
19
+
20
+ import type { SitePreset } from './policy/presets.ts';
21
+
22
+ import { logger } from './logger.ts';
23
+ import { addPreset, normalizeSiteKey } from './policy/presets.ts';
24
+
25
+ export const PRESETS_DIR_ENV = 'READABILITY_PRESETS_DIR';
26
+
27
+ export const MAX_PRESET_FILES = 64;
28
+
29
+ // An empty scope applies nothing while reporting applied:true, and detectors
30
+ // only mean something as a non-empty set — reject both at the file boundary.
31
+ const presetFileSchema = z.object({
32
+ site: z.string().min(1),
33
+ detectors: z.array(z.string().min(1)).min(1),
34
+ scope: z
35
+ .object({
36
+ include: z.string().min(1).optional(),
37
+ exclude: z.array(z.string().min(1)).min(1).optional(),
38
+ })
39
+ .refine(
40
+ scope => scope.include !== undefined || scope.exclude !== undefined,
41
+ {
42
+ message: 'scope must carry include or exclude',
43
+ },
44
+ ),
45
+ });
46
+
47
+ export interface PresetCacheReport {
48
+ readonly loaded: number;
49
+ readonly pruned: number;
50
+ readonly skipped: number;
51
+ }
52
+
53
+ // Empty string disables preset loading; an absolute path wins over the
54
+ // platform default.
55
+ export function resolvePresetsDir(
56
+ env: NodeJS.ProcessEnv = process.env,
57
+ ): string | undefined {
58
+ const override = env[PRESETS_DIR_ENV];
59
+ if (override !== undefined) {
60
+ return override.trim() === '' ? undefined : override;
61
+ }
62
+ const root =
63
+ env.XDG_CACHE_HOME ||
64
+ join(
65
+ homedir(),
66
+ process.platform === 'darwin' ? 'Library/Caches' : '.cache',
67
+ );
68
+ return join(root, 'readability', 'presets');
69
+ }
70
+
71
+ // A preset that cannot load is a warning, never a boot failure — the pipeline
72
+ // is designed to run without one.
73
+ export function loadPresetDir(dir: string): PresetCacheReport {
74
+ let names: string[];
75
+ try {
76
+ names = readdirSync(dir)
77
+ .filter(name => name.endsWith('.json'))
78
+ .sort();
79
+ } catch (err) {
80
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') {
81
+ logger.debug(`no preset directory at ${dir}`);
82
+ } else {
83
+ logger.warn(`preset directory unreadable: ${dir}`);
84
+ }
85
+ return { loaded: 0, pruned: 0, skipped: 0 };
86
+ }
87
+
88
+ const ranked = rankPresetFiles(dir, names);
89
+
90
+ const pruned = pruneRanked(dir, ranked.slice(MAX_PRESET_FILES));
91
+
92
+ let loaded = 0;
93
+ let skipped = 0;
94
+ for (const { name } of ranked.slice(0, MAX_PRESET_FILES)) {
95
+ const path = join(dir, name);
96
+ if (loadPresetFile(path)) {
97
+ loaded++;
98
+ } else {
99
+ skipped++;
100
+ }
101
+ }
102
+ if (loaded > 0) {
103
+ logger.info(`loaded ${loaded} site preset(s) from ${dir}`);
104
+ }
105
+ if (pruned > 0) {
106
+ logger.info(
107
+ `pruned ${pruned} preset file(s) beyond the ${MAX_PRESET_FILES}-file bound`,
108
+ );
109
+ }
110
+ return { loaded, pruned, skipped };
111
+ }
112
+
113
+ // Env-resolving entry point for the boot paths; undefined means disabled.
114
+ export function loadPresets(
115
+ env: NodeJS.ProcessEnv = process.env,
116
+ ): PresetCacheReport | undefined {
117
+ const dir = resolvePresetsDir(env);
118
+ return dir ? loadPresetDir(dir) : undefined;
119
+ }
120
+
121
+ function rankPresetFiles(
122
+ dir: string,
123
+ names: string[],
124
+ ): { mtimeMs: number; name: string }[] {
125
+ const ranked: { mtimeMs: number; name: string }[] = [];
126
+ for (const name of names) {
127
+ try {
128
+ ranked.push({ name, mtimeMs: statSync(join(dir, name)).mtimeMs });
129
+ } catch {
130
+ // Vanished between readdir and stat — nothing to load or prune.
131
+ }
132
+ }
133
+ ranked.sort((a, b) => b.mtimeMs - a.mtimeMs);
134
+ return ranked;
135
+ }
136
+
137
+ function pruneRanked(
138
+ dir: string,
139
+ ranked: { mtimeMs: number; name: string }[],
140
+ ): number {
141
+ let pruned = 0;
142
+ for (const { name } of ranked) {
143
+ try {
144
+ unlinkSync(join(dir, name));
145
+ pruned++;
146
+ } catch (err) {
147
+ logger.warn(`could not prune preset file ${name}: ${describeError(err)}`);
148
+ }
149
+ }
150
+ return pruned;
151
+ }
152
+
153
+ export interface PersistReport {
154
+ readonly path?: string;
155
+ readonly persisted: boolean;
156
+ readonly reason?: string;
157
+ }
158
+
159
+ // The writer the loader was waiting for: the suggest loop saves an accepted
160
+ // preset so the next server start loads it like any hand-placed file. A
161
+ // failure leaves the in-memory preset working — persistence is best-effort,
162
+ // exactly like loading.
163
+ export function savePreset(
164
+ preset: SitePreset,
165
+ env: NodeJS.ProcessEnv = process.env,
166
+ ): PersistReport {
167
+ const dir = resolvePresetsDir(env);
168
+ if (!dir) {
169
+ return { persisted: false, reason: 'preset-directory-disabled' };
170
+ }
171
+ const shape = presetFileSchema.safeParse(preset);
172
+ if (!shape.success) {
173
+ return {
174
+ persisted: false,
175
+ reason: shape.error.issues[0]?.message ?? 'invalid preset shape',
176
+ };
177
+ }
178
+ const key = normalizeSiteKey(preset.site);
179
+ if (!key) {
180
+ return { persisted: false, reason: 'site-is-not-a-hostname' };
181
+ }
182
+ const path = join(dir, `${key}.json`);
183
+ try {
184
+ mkdirSync(dir, { recursive: true });
185
+ writeFileSync(path, `${JSON.stringify(shape.data, null, 2)}\n`);
186
+ } catch (err) {
187
+ return {
188
+ persisted: false,
189
+ reason: describeError(err),
190
+ };
191
+ }
192
+ const over = rankPresetFiles(
193
+ dir,
194
+ readdirSync(dir).filter(name => name.endsWith('.json')),
195
+ );
196
+ pruneRanked(dir, over.slice(MAX_PRESET_FILES));
197
+ return { path, persisted: true };
198
+ }
199
+
200
+ function loadPresetFile(path: string): boolean {
201
+ let parsed: unknown;
202
+ try {
203
+ parsed = JSON.parse(readFileSync(path, 'utf8')) as unknown;
204
+ } catch (err) {
205
+ logger.warn(
206
+ `${path}: not readable JSON (${describeError(err)}), preset skipped`,
207
+ );
208
+ return false;
209
+ }
210
+ const result = presetFileSchema.safeParse(parsed);
211
+ if (!result.success) {
212
+ logger.warn(`${path}: ${result.error.issues[0]?.message}, preset skipped`);
213
+ return false;
214
+ }
215
+ if (!normalizeSiteKey(result.data.site)) {
216
+ logger.warn(`${path}: site is not a hostname, preset skipped`);
217
+ return false;
218
+ }
219
+ addPreset(result.data);
220
+ return true;
221
+ }
@@ -0,0 +1,317 @@
1
+ // In-memory cache of extract results keyed by a volatility-normalized hash of
2
+ // the HTML plus an args fingerprint, exposed to clients as addressable MCP
3
+ // Resources (`readability://page/{hash}`). Re-renders that differ only in
4
+ // nonce/CSP/generated ids collapse to the same key; the original hash rides
5
+ // alongside each entry so a should-have-hit-but-didn't miss points at a
6
+ // normalizer bug rather than a genuinely different page.
7
+
8
+ import { ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';
9
+ import { createHash } from 'node:crypto';
10
+
11
+ import type { ToolHandle } from './server.ts';
12
+ import type { ExtractFromHtmlInput } from './tools/schemas.ts';
13
+
14
+ import { presetGeneration } from './policy/presets.ts';
15
+
16
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
17
+ import type {
18
+ ListResourcesResult,
19
+ ReadResourceResult,
20
+ } from '@modelcontextprotocol/sdk/types.js';
21
+
22
+ const MAX_ENTRIES = 256;
23
+ const TTL_MS = 30 * 60 * 1000;
24
+ const RESOURCE_SCHEME = 'readability://page/';
25
+
26
+ interface CacheEntry {
27
+ readonly argsFingerprint: string;
28
+ readonly cacheKey: string;
29
+ readonly contentText: string;
30
+ readonly expiresAt: number;
31
+ readonly normalizedHash: string;
32
+ readonly originalHash: string;
33
+ // Held opaquely: cloned on hit and returned as CallToolResult.structuredContent
34
+ // without re-validation, so a wider element type than the strict output schema
35
+ // (e.g. readonly trace arrays) is fine here.
36
+ readonly structuredContent: unknown;
37
+ }
38
+
39
+ interface CacheLookup {
40
+ readonly entry: CacheEntry;
41
+ readonly normalizedHash: string;
42
+ readonly originalHash: string;
43
+ }
44
+
45
+ const entries = new Map<string, CacheEntry>();
46
+
47
+ export function resetCache(): void {
48
+ entries.clear();
49
+ }
50
+
51
+ function evictExpired(now: number): void {
52
+ for (const [key, entry] of entries) {
53
+ if (entry.expiresAt <= now) {
54
+ entries.delete(key);
55
+ }
56
+ }
57
+ }
58
+
59
+ // Bounded LRU: Map preserves insertion order, so re-insert on access to surface
60
+ // recently-used entries to the end and drop the oldest when over capacity.
61
+ function touch(key: string, entry: CacheEntry): void {
62
+ entries.delete(key);
63
+ entries.set(key, entry);
64
+ }
65
+
66
+ function pruneToMax(): void {
67
+ while (entries.size > MAX_ENTRIES) {
68
+ const oldest = entries.keys().next();
69
+ if (oldest.done) {
70
+ break;
71
+ }
72
+ entries.delete(oldest.value);
73
+ }
74
+ }
75
+
76
+ // --- Hashing ---------------------------------------------------------------
77
+
78
+ // Conservative volatility normalization — over-stripping collides distinct
79
+ // pages. Each rule targets a specific known-volatile source.
80
+ function normalizeForHash(html: string): string {
81
+ let s = html;
82
+ // Non-JSON-LD scripts carry CSP nonces, build hashes, A/B test buckets —
83
+ // same page, different bytes on every render — so strip them. Preserve
84
+ // <script type="application/ld+json">: structured metadata is content, so
85
+ // a changed datePublished must bust the cache. Mirrors the extraction
86
+ // normalizer in pipeline/normalize.ts.
87
+ s = s.replace(
88
+ /<script\b(?![^>]*type\s*=\s*["']application\/ld\+json["'])[^>]*>[\s\S]*?<\/script>/gi,
89
+ '',
90
+ );
91
+ s = s.replace(
92
+ /<script\b(?![^>]*type\s*=\s*["']application\/ld\+json["'])[^>]*\/?>/gi,
93
+ '',
94
+ );
95
+ // CSP <meta http-equiv="Content-Security-Policy"> carries the per-response
96
+ // nonce directive — strip the whole tag.
97
+ s = s.replace(
98
+ /<meta\b[^>]*http-equiv=["']?content-security-policy["']?[^>]*>/gi,
99
+ '',
100
+ );
101
+ // Per-render nonce attributes on any tag (script, link, style, …).
102
+ s = s.replace(/\snonce\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/gi, '');
103
+ // Build-tool generated attribute names: Vue `data-v-1a2b3c4d`,
104
+ // CSS-modules `data-css-1a2b3c4d`, Svelte `data-svelte-1a2b3c4d`. The
105
+ // value-part is optional — Vue's compiler emits the bare `data-v-<hash>`
106
+ // form with no `="..."`.
107
+ s = s.replace(
108
+ /\sdata-(?:v|css|svelte|h)-[a-z0-9]{6,}(?:\s*=\s*("[^"]*"|'[^']*'|[^\s>]+))?/gi,
109
+ '',
110
+ );
111
+ // React useId / RSC / Next.js generated ids: id=":R1:", ':r1:',
112
+ // __next_internal_action_…, react internal identifiers.
113
+ s = s.replace(
114
+ /\sid\s*=\s*(":[A-Za-z0-9_-]+:"|':[A-Za-z0-9_-]+:'|__next_[A-Za-z0-9_-]+)/g,
115
+ '',
116
+ );
117
+ s = s.replace(
118
+ /\sid\s*=\s*("react[A-Z]_[A-Za-z0-9_]+"|'react[A-Z]_[A-Za-z0-9_]+')/gi,
119
+ '',
120
+ );
121
+ // Whitespace runs and indentation differ by minifier/pretty-printer.
122
+ s = s.replace(/\s+/g, ' ');
123
+ return s.trim();
124
+ }
125
+
126
+ function sha256(text: string): string {
127
+ return createHash('sha256').update(text).digest('hex');
128
+ }
129
+
130
+ export function normalizedHashOf(html: string): string {
131
+ return sha256(normalizeForHash(html));
132
+ }
133
+
134
+ export function originalHashOf(html: string): string {
135
+ return sha256(html.trim());
136
+ }
137
+
138
+ // Output-affecting options participate in the fingerprint so the same page with
139
+ // format:'html' vs format:'markdown' does not collide. `baseUrl` absolutizes
140
+ // links in the output, so it must participate too. The preset generation rides
141
+ // in the fingerprint rather than the resolved scope: an entry extracted before
142
+ // a preset landed must never be served after it, and hashing the scope would
143
+ // need a second document parse while conflating applied and missed runs under
144
+ // one key.
145
+ function buildArgsFingerprint(args: ExtractFromHtmlInput): string {
146
+ const sel = args.selectors
147
+ ? {
148
+ exclude: args.selectors.exclude ?? [],
149
+ include: args.selectors.include ?? '',
150
+ }
151
+ : null;
152
+ const chunk = args.chunk
153
+ ? {
154
+ maxTokens: args.chunk.maxTokens,
155
+ overlap: args.chunk.overlap,
156
+ strategy: args.chunk.strategy,
157
+ }
158
+ : null;
159
+ const fp = {
160
+ chunk,
161
+ cleanChrome: args.cleanChrome,
162
+ codeBlockStyle: args.codeBlockStyle,
163
+ debug: args.debug,
164
+ extraction: args.extraction,
165
+ format: args.format,
166
+ gfm: args.gfm,
167
+ headingStyle: args.headingStyle,
168
+ imageInventory: args.imageInventory,
169
+ images: args.images,
170
+ keepClasses: args.keepClasses,
171
+ maxChars: args.maxChars ?? null,
172
+ maxNodes: args.maxNodes ?? null,
173
+ metadataMode: args.metadataMode,
174
+ minArticleLength: args.minArticleLength ?? null,
175
+ presetGeneration: presetGeneration(),
176
+ readabilityOverrides: args.readabilityOverrides ?? null,
177
+ sanitize: args.sanitize,
178
+ selectors: sel,
179
+ tables: args.tables ?? null,
180
+ baseUrl: args.baseUrl ?? null,
181
+ wordsPerMinute: args.wordsPerMinute,
182
+ };
183
+ return JSON.stringify(fp);
184
+ }
185
+
186
+ function computeHashes(html: string): {
187
+ normalizedHash: string;
188
+ originalHash: string;
189
+ } {
190
+ return {
191
+ normalizedHash: normalizedHashOf(html),
192
+ originalHash: originalHashOf(html),
193
+ };
194
+ }
195
+
196
+ function combineKey(normalizedHash: string, argsFingerprint: string): string {
197
+ return sha256(`${normalizedHash}:${argsFingerprint}`);
198
+ }
199
+
200
+ // --- Store API -------------------------------------------------------------
201
+
202
+ export function lookup(
203
+ html: string,
204
+ args: ExtractFromHtmlInput,
205
+ ): CacheLookup | undefined {
206
+ const now = Date.now();
207
+ evictExpired(now);
208
+ const { normalizedHash, originalHash } = computeHashes(html);
209
+ const cacheKey = combineKey(normalizedHash, buildArgsFingerprint(args));
210
+ const entry = entries.get(cacheKey);
211
+ if (!entry || entry.expiresAt <= now) {
212
+ if (entry) {
213
+ entries.delete(cacheKey);
214
+ }
215
+ return undefined;
216
+ }
217
+ touch(cacheKey, entry);
218
+ return { entry, normalizedHash, originalHash };
219
+ }
220
+
221
+ export function storeResult(
222
+ html: string,
223
+ args: ExtractFromHtmlInput,
224
+ result: {
225
+ contentText: string;
226
+ structuredContent: unknown;
227
+ },
228
+ ): { normalizedHash: string; originalHash: string } {
229
+ const now = Date.now();
230
+ evictExpired(now);
231
+ const { normalizedHash, originalHash } = computeHashes(html);
232
+ const argsFingerprint = buildArgsFingerprint(args);
233
+ const cacheKey = combineKey(normalizedHash, argsFingerprint);
234
+ const entry: CacheEntry = {
235
+ argsFingerprint,
236
+ cacheKey,
237
+ contentText: result.contentText,
238
+ expiresAt: now + TTL_MS,
239
+ normalizedHash,
240
+ originalHash,
241
+ structuredContent: result.structuredContent,
242
+ };
243
+ entries.set(cacheKey, entry);
244
+ pruneToMax();
245
+ return { normalizedHash, originalHash };
246
+ }
247
+
248
+ export function getEntryByHash(hash: string): CacheEntry | undefined {
249
+ for (const entry of entries.values()) {
250
+ if (entry.normalizedHash === hash || entry.cacheKey === hash) {
251
+ return entry;
252
+ }
253
+ }
254
+ return undefined;
255
+ }
256
+
257
+ export function listEntries(): readonly CacheEntry[] {
258
+ const now = Date.now();
259
+ evictExpired(now);
260
+ return [...entries.values()];
261
+ }
262
+
263
+ // --- Resource registration -------------------------------------------------
264
+
265
+ // "page-cache" names the registered template; the readability:// URI scheme
266
+ // identifies the cache namespace and {hash} is the combined cache key.
267
+ const PAGE_CACHE_TEMPLATE = new ResourceTemplate('readability://page/{hash}', {
268
+ // Dynamic set: the cache comes and goes, so we enumerate current entries.
269
+ list: (): ListResourcesResult => ({
270
+ resources: listEntries().map(entry => ({
271
+ description: `Cached extract for normalized hash ${entry.normalizedHash.slice(0, 12)}…`,
272
+ mimeType: 'text/markdown',
273
+ name: entry.normalizedHash,
274
+ uri: `${RESOURCE_SCHEME}${entry.cacheKey}`,
275
+ })),
276
+ }),
277
+ });
278
+
279
+ export function registerCacheResources(server: McpServer): ToolHandle {
280
+ return server.registerResource(
281
+ 'page-cache',
282
+ PAGE_CACHE_TEMPLATE,
283
+ {
284
+ title: 'Cached page extractions',
285
+ description:
286
+ 'Addressable cache of `extract` results called with cache:true. Each entry is keyed by the volatility-normalized hash of the HTML plus the output options; the URI path segment is the combined cache key.',
287
+ mimeType: 'text/markdown',
288
+ },
289
+ (uri, variables): ReadResourceResult => {
290
+ const hash = String(variables.hash);
291
+ const entry = getEntryByHash(hash);
292
+ if (!entry) {
293
+ return {
294
+ contents: [
295
+ {
296
+ uri: uri.href,
297
+ text: '',
298
+ },
299
+ ],
300
+ };
301
+ }
302
+ return {
303
+ contents: [
304
+ {
305
+ uri: uri.href,
306
+ mimeType: 'text/markdown',
307
+ text: entry.contentText,
308
+ },
309
+ ],
310
+ };
311
+ },
312
+ );
313
+ }
314
+
315
+ export function registerResources(server: McpServer): ToolHandle[] {
316
+ return [registerCacheResources(server)];
317
+ }
@@ -0,0 +1,74 @@
1
+ // Optional, capability-gated tools backed by the HOST's model. The sampling
2
+ // seam itself lives in host-sampling.ts; this file owns the family's tool
3
+ // registrations.
4
+
5
+ import { z } from 'zod';
6
+
7
+ import type { ToolHandle } from './server.ts';
8
+
9
+ import { tool } from './handler.ts';
10
+ import { sampleText } from './host-sampling.ts';
11
+ import { registerSuggestPresetTool } from './tools/suggest-preset.ts';
12
+
13
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
14
+
15
+ const SUMMARIZE_SYSTEM_PROMPT =
16
+ 'Summarize the user-supplied text concisely while preserving its key points, entities, and any decisive conclusions. Output only the summary prose — no preamble, no headings unless the source had them.';
17
+
18
+ const summarizeInputShape = {
19
+ text: z
20
+ .string()
21
+ .describe(
22
+ 'The markdown or text to summarize — typically the output of `extract`, `extract_section`, `html_to_markdown`, or `chunk_text`. Passed through to the host model verbatim; the server does not parse or modify it.',
23
+ ),
24
+ maxTokens: z
25
+ .number()
26
+ .int()
27
+ .min(1)
28
+ .describe(
29
+ 'Ceiling on tokens the host model may generate, forwarded as `sampling/createMessage` maxTokens. Thinking counts toward it on thinking models, so a low value truncates the summary; the system prompt already asks for a concise one.',
30
+ )
31
+ .default(4096),
32
+ } as const;
33
+
34
+ const summarizeInputSchema = z.object(summarizeInputShape);
35
+
36
+ export const SUMMARIZE_TOOL_DESCRIPTION = `Summarize text using the HOST's model via MCP \`sampling/createMessage\` — the server embeds no model and calls no provider directly. Hand it the output of \`extract\`, \`extract_section\`, \`html_to_markdown\`, or any markdown/text string; the host picks the model and may ask the user to approve the sampling request (human-in-the-loop per MCP). The tool is only listed when the connected client advertises the sampling capability.`;
37
+
38
+ async function summarizeWithHost(
39
+ server: McpServer,
40
+ args: { maxTokens: number; text: string },
41
+ ): Promise<string> {
42
+ return sampleText(server, {
43
+ maxTokens: args.maxTokens,
44
+ systemPrompt: SUMMARIZE_SYSTEM_PROMPT,
45
+ userText: args.text,
46
+ });
47
+ }
48
+
49
+ export function registerSummarizeTool(server: McpServer): ToolHandle {
50
+ return server.registerTool(
51
+ 'summarize',
52
+ {
53
+ title: 'Summarize text using the host model',
54
+ description: SUMMARIZE_TOOL_DESCRIPTION,
55
+ inputSchema: summarizeInputShape,
56
+ },
57
+ tool(
58
+ 'summarize',
59
+ async args => {
60
+ const summary = await summarizeWithHost(server, args);
61
+ return {
62
+ content: [{ type: 'text', text: summary }],
63
+ };
64
+ },
65
+ summarizeInputSchema,
66
+ ),
67
+ );
68
+ }
69
+
70
+ // Mirrors registerTools/registerResources so the dev reload
71
+ // loop and capability gate can treat sampling as one registration family.
72
+ export function registerSamplingTools(server: McpServer): ToolHandle[] {
73
+ return [registerSummarizeTool(server), registerSuggestPresetTool(server)];
74
+ }