@v1nvn/readability 0.44.0 → 0.45.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 +3 -3
- package/package.json +7 -9
- package/src/cli.js +99 -0
- package/src/cli.ts +134 -0
- package/src/config.js +29 -0
- package/src/config.ts +42 -0
- package/src/dev.js +55 -0
- package/src/dev.ts +77 -0
- package/src/errors.js +16 -0
- package/src/errors.ts +19 -0
- package/src/handler.js +4 -0
- package/src/handler.ts +8 -0
- package/src/host-sampling.js +57 -0
- package/src/host-sampling.ts +86 -0
- package/src/index.js +23 -0
- package/src/index.ts +27 -0
- package/src/logger.js +2 -0
- package/src/logger.ts +3 -0
- package/src/output/format.js +92 -0
- package/src/output/format.ts +132 -0
- package/src/pipeline/cell-text.js +51 -0
- package/src/pipeline/cell-text.ts +56 -0
- package/src/pipeline/context.js +1 -0
- package/src/pipeline/context.ts +88 -0
- package/src/pipeline/dom.js +16 -0
- package/src/pipeline/dom.ts +23 -0
- package/src/pipeline/footnotes.js +148 -0
- package/src/pipeline/footnotes.ts +181 -0
- package/src/pipeline/math.js +113 -0
- package/src/pipeline/math.ts +130 -0
- package/src/pipeline/normalize.js +507 -0
- package/src/pipeline/normalize.ts +594 -0
- package/src/pipeline/readability.js +10 -0
- package/src/pipeline/readability.ts +36 -0
- package/src/pipeline/resolver.js +113 -0
- package/src/pipeline/resolver.ts +143 -0
- package/src/pipeline/sanitize.js +26 -0
- package/src/pipeline/sanitize.ts +42 -0
- package/src/pipeline/tables.js +239 -0
- package/src/pipeline/tables.ts +286 -0
- package/src/pipeline/turndown.js +153 -0
- package/src/pipeline/turndown.ts +191 -0
- package/src/pipeline/urls.js +14 -0
- package/src/pipeline/urls.ts +13 -0
- package/src/policy/chunk.js +365 -0
- package/src/policy/chunk.ts +482 -0
- package/src/policy/diagnostics.js +53 -0
- package/src/policy/diagnostics.ts +96 -0
- package/src/policy/explain.js +104 -0
- package/src/policy/explain.ts +182 -0
- package/src/policy/fallback.js +68 -0
- package/src/policy/fallback.ts +110 -0
- package/src/policy/gating.js +90 -0
- package/src/policy/gating.ts +106 -0
- package/src/policy/grid-detector.js +207 -0
- package/src/policy/grid-detector.ts +313 -0
- package/src/policy/identifiers.js +62 -0
- package/src/policy/identifiers.ts +75 -0
- package/src/policy/images.js +49 -0
- package/src/policy/images.ts +64 -0
- package/src/policy/list-detector.js +232 -0
- package/src/policy/list-detector.ts +308 -0
- package/src/policy/lost-signal.js +44 -0
- package/src/policy/lost-signal.ts +69 -0
- package/src/policy/markdown.js +58 -0
- package/src/policy/markdown.ts +76 -0
- package/src/policy/metadata.js +216 -0
- package/src/policy/metadata.ts +312 -0
- package/src/policy/outline-chains.js +165 -0
- package/src/policy/outline-chains.ts +215 -0
- package/src/policy/outline.js +71 -0
- package/src/policy/outline.ts +89 -0
- package/src/policy/pagination.js +79 -0
- package/src/policy/pagination.ts +104 -0
- package/src/policy/presets.js +100 -0
- package/src/policy/presets.ts +142 -0
- package/src/policy/section.js +111 -0
- package/src/policy/section.ts +127 -0
- package/src/policy/selector-lint.js +143 -0
- package/src/policy/selector-lint.ts +186 -0
- package/src/policy/sibling-scan.js +92 -0
- package/src/policy/sibling-scan.ts +99 -0
- package/src/policy/text.js +18 -0
- package/src/policy/text.ts +36 -0
- package/src/policy/truncate.js +45 -0
- package/src/policy/truncate.ts +59 -0
- package/src/preset-cache.js +165 -0
- package/src/preset-cache.ts +221 -0
- package/src/resources.js +227 -0
- package/src/resources.ts +317 -0
- package/src/sampling.js +45 -0
- package/src/sampling.ts +74 -0
- package/src/server.js +73 -0
- package/src/server.ts +85 -0
- package/src/tools/chunk_text.js +40 -0
- package/src/tools/chunk_text.ts +65 -0
- package/src/tools/explain.js +200 -0
- package/src/tools/explain.ts +299 -0
- package/src/tools/extract.js +263 -0
- package/src/tools/extract.ts +368 -0
- package/src/tools/extract_grid.js +56 -0
- package/src/tools/extract_grid.ts +90 -0
- package/src/tools/extract_links.js +98 -0
- package/src/tools/extract_links.ts +138 -0
- package/src/tools/extract_list.js +66 -0
- package/src/tools/extract_list.ts +97 -0
- package/src/tools/extract_metadata.js +67 -0
- package/src/tools/extract_metadata.ts +102 -0
- package/src/tools/extract_section.js +56 -0
- package/src/tools/extract_section.ts +84 -0
- package/src/tools/extract_tables.js +59 -0
- package/src/tools/extract_tables.ts +101 -0
- package/src/tools/html-source.js +30 -0
- package/src/tools/html-source.ts +40 -0
- package/src/tools/html_to_markdown.js +113 -0
- package/src/tools/html_to_markdown.ts +180 -0
- package/src/tools/outline.js +47 -0
- package/src/tools/outline.ts +77 -0
- package/src/tools/output-schema.js +504 -0
- package/src/tools/output-schema.ts +715 -0
- package/src/tools/schemas.js +288 -0
- package/src/tools/schemas.ts +442 -0
- package/src/tools/suggest-preset.js +504 -0
- package/src/tools/suggest-preset.ts +708 -0
- package/src/types/jsdom.d.ts +15 -0
- package/src/types/turndown-plugin-gfm.d.ts +11 -0
- package/dist/assets/cli-Dfjg7dOQ.js +0 -76
- package/dist/assets/cli-Dfjg7dOQ.js.map +0 -1
- package/dist/assets/extract-CdDp-KwX.js +0 -2880
- package/dist/assets/extract-CdDp-KwX.js.map +0 -1
- package/dist/index.js +0 -2267
- package/dist/index.js.map +0 -1
package/src/server.js
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
2
|
+
import { loadConfig } from "./config.js";
|
|
3
|
+
import { loadPresets } from "./preset-cache.js";
|
|
4
|
+
import { registerResources } from "./resources.js";
|
|
5
|
+
import { registerSamplingTools } from "./sampling.js";
|
|
6
|
+
import { registerChunkTextTool } from "./tools/chunk_text.js";
|
|
7
|
+
import { registerExplainTool } from "./tools/explain.js";
|
|
8
|
+
import { registerExtractGridTool } from "./tools/extract_grid.js";
|
|
9
|
+
import { registerExtractLinksTool } from "./tools/extract_links.js";
|
|
10
|
+
import { registerExtractListTool } from "./tools/extract_list.js";
|
|
11
|
+
import { registerExtractMetadataTool } from "./tools/extract_metadata.js";
|
|
12
|
+
import { registerExtractSectionTool } from "./tools/extract_section.js";
|
|
13
|
+
import { registerExtractTablesTool } from "./tools/extract_tables.js";
|
|
14
|
+
import { registerExtractTool } from "./tools/extract.js";
|
|
15
|
+
import { registerHtmlToMarkdownTool } from "./tools/html_to_markdown.js";
|
|
16
|
+
import { registerOutlineTool } from "./tools/outline.js";
|
|
17
|
+
// Re-exported so the dev hot-reload loop can import server.ts as a single
|
|
18
|
+
// RuntimeModule and pick up every registration family (tools/resources) plus
|
|
19
|
+
// the boot-time preset load.
|
|
20
|
+
export { loadPresets, registerResources };
|
|
21
|
+
export function createMcpServer() {
|
|
22
|
+
const { name, version, title, description, instructions } = loadConfig();
|
|
23
|
+
return new McpServer({ name, version, title, description }, { instructions });
|
|
24
|
+
}
|
|
25
|
+
// A tool earns its place only by skipping a pipeline stage (outline,
|
|
26
|
+
// extract_metadata skip Readability) or returning a fundamentally different
|
|
27
|
+
// shape (extract_list is a second engine). Alternate views of the one pipeline
|
|
28
|
+
// — tables, images, structured data, code — are options or fields on `extract`,
|
|
29
|
+
// not separate tools; that keeps the MCP surface small and the pipeline deep.
|
|
30
|
+
export function registerTools(server) {
|
|
31
|
+
return [
|
|
32
|
+
registerChunkTextTool(server),
|
|
33
|
+
registerExplainTool(server),
|
|
34
|
+
registerExtractGridTool(server),
|
|
35
|
+
registerExtractLinksTool(server),
|
|
36
|
+
registerExtractListTool(server),
|
|
37
|
+
registerExtractTool(server),
|
|
38
|
+
registerExtractMetadataTool(server),
|
|
39
|
+
registerExtractSectionTool(server),
|
|
40
|
+
registerExtractTablesTool(server),
|
|
41
|
+
registerHtmlToMarkdownTool(server),
|
|
42
|
+
registerOutlineTool(server),
|
|
43
|
+
];
|
|
44
|
+
}
|
|
45
|
+
// Capability-gated tools are registered AFTER the initialize handshake, not
|
|
46
|
+
// eagerly with the families above. The MCP `tools` capability locks in on the
|
|
47
|
+
// first pre-connect registration (registerCapabilities throws post-connect),
|
|
48
|
+
// so the tool-list handlers are already live; adding to `_registeredTools`
|
|
49
|
+
// later simply appears in the next `tools/list` and fires `listChanged`. The
|
|
50
|
+
// low-level Server populates `getClientCapabilities()` from the client's
|
|
51
|
+
// `initialize` request, exposed via `McpServer.server`.
|
|
52
|
+
export function registerCapabilityGatedTools(server) {
|
|
53
|
+
const caps = server.server.getClientCapabilities();
|
|
54
|
+
if (!caps?.sampling) {
|
|
55
|
+
return [];
|
|
56
|
+
}
|
|
57
|
+
return registerSamplingTools(server);
|
|
58
|
+
}
|
|
59
|
+
export function createServer() {
|
|
60
|
+
const server = createMcpServer();
|
|
61
|
+
loadPresets();
|
|
62
|
+
registerTools(server);
|
|
63
|
+
registerResources(server);
|
|
64
|
+
// Capability-gated tools (sampling) need the client's advertised
|
|
65
|
+
// capabilities, which the low-level Server only populates after the
|
|
66
|
+
// initialize handshake. Hook the `initialized` notification — it fires once
|
|
67
|
+
// the client has connected and before any `tools/list`. `dev.ts` re-runs the
|
|
68
|
+
// gate directly on reload (the client is already past `initialized`).
|
|
69
|
+
server.server.oninitialized = () => {
|
|
70
|
+
registerCapabilityGatedTools(server);
|
|
71
|
+
};
|
|
72
|
+
return server;
|
|
73
|
+
}
|
package/src/server.ts
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
2
|
+
|
|
3
|
+
import { loadConfig } from './config.ts';
|
|
4
|
+
import { loadPresets } from './preset-cache.ts';
|
|
5
|
+
import { registerResources } from './resources.ts';
|
|
6
|
+
import { registerSamplingTools } from './sampling.ts';
|
|
7
|
+
import { registerChunkTextTool } from './tools/chunk_text.ts';
|
|
8
|
+
import { registerExplainTool } from './tools/explain.ts';
|
|
9
|
+
import { registerExtractGridTool } from './tools/extract_grid.ts';
|
|
10
|
+
import { registerExtractLinksTool } from './tools/extract_links.ts';
|
|
11
|
+
import { registerExtractListTool } from './tools/extract_list.ts';
|
|
12
|
+
import { registerExtractMetadataTool } from './tools/extract_metadata.ts';
|
|
13
|
+
import { registerExtractSectionTool } from './tools/extract_section.ts';
|
|
14
|
+
import { registerExtractTablesTool } from './tools/extract_tables.ts';
|
|
15
|
+
import { registerExtractTool } from './tools/extract.ts';
|
|
16
|
+
import { registerHtmlToMarkdownTool } from './tools/html_to_markdown.ts';
|
|
17
|
+
import { registerOutlineTool } from './tools/outline.ts';
|
|
18
|
+
|
|
19
|
+
// Re-exported so the dev hot-reload loop can import server.ts as a single
|
|
20
|
+
// RuntimeModule and pick up every registration family (tools/resources) plus
|
|
21
|
+
// the boot-time preset load.
|
|
22
|
+
export { loadPresets, registerResources };
|
|
23
|
+
|
|
24
|
+
// `remove()` unregisters the tool and notifies the client; dev reload holds the
|
|
25
|
+
// previous batch to remove before re-registering.
|
|
26
|
+
export interface ToolHandle {
|
|
27
|
+
remove(): void;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function createMcpServer(): McpServer {
|
|
31
|
+
const { name, version, title, description, instructions } = loadConfig();
|
|
32
|
+
return new McpServer({ name, version, title, description }, { instructions });
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// A tool earns its place only by skipping a pipeline stage (outline,
|
|
36
|
+
// extract_metadata skip Readability) or returning a fundamentally different
|
|
37
|
+
// shape (extract_list is a second engine). Alternate views of the one pipeline
|
|
38
|
+
// — tables, images, structured data, code — are options or fields on `extract`,
|
|
39
|
+
// not separate tools; that keeps the MCP surface small and the pipeline deep.
|
|
40
|
+
export function registerTools(server: McpServer): ToolHandle[] {
|
|
41
|
+
return [
|
|
42
|
+
registerChunkTextTool(server),
|
|
43
|
+
registerExplainTool(server),
|
|
44
|
+
registerExtractGridTool(server),
|
|
45
|
+
registerExtractLinksTool(server),
|
|
46
|
+
registerExtractListTool(server),
|
|
47
|
+
registerExtractTool(server),
|
|
48
|
+
registerExtractMetadataTool(server),
|
|
49
|
+
registerExtractSectionTool(server),
|
|
50
|
+
registerExtractTablesTool(server),
|
|
51
|
+
registerHtmlToMarkdownTool(server),
|
|
52
|
+
registerOutlineTool(server),
|
|
53
|
+
];
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// Capability-gated tools are registered AFTER the initialize handshake, not
|
|
57
|
+
// eagerly with the families above. The MCP `tools` capability locks in on the
|
|
58
|
+
// first pre-connect registration (registerCapabilities throws post-connect),
|
|
59
|
+
// so the tool-list handlers are already live; adding to `_registeredTools`
|
|
60
|
+
// later simply appears in the next `tools/list` and fires `listChanged`. The
|
|
61
|
+
// low-level Server populates `getClientCapabilities()` from the client's
|
|
62
|
+
// `initialize` request, exposed via `McpServer.server`.
|
|
63
|
+
export function registerCapabilityGatedTools(server: McpServer): ToolHandle[] {
|
|
64
|
+
const caps = server.server.getClientCapabilities();
|
|
65
|
+
if (!caps?.sampling) {
|
|
66
|
+
return [];
|
|
67
|
+
}
|
|
68
|
+
return registerSamplingTools(server);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function createServer(): McpServer {
|
|
72
|
+
const server = createMcpServer();
|
|
73
|
+
loadPresets();
|
|
74
|
+
registerTools(server);
|
|
75
|
+
registerResources(server);
|
|
76
|
+
// Capability-gated tools (sampling) need the client's advertised
|
|
77
|
+
// capabilities, which the low-level Server only populates after the
|
|
78
|
+
// initialize handshake. Hook the `initialized` notification — it fires once
|
|
79
|
+
// the client has connected and before any `tools/list`. `dev.ts` re-runs the
|
|
80
|
+
// gate directly on reload (the client is already past `initialized`).
|
|
81
|
+
server.server.oninitialized = () => {
|
|
82
|
+
registerCapabilityGatedTools(server);
|
|
83
|
+
};
|
|
84
|
+
return server;
|
|
85
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { tool } from "../handler.js";
|
|
2
|
+
import { chunkMarkdown } from "../policy/chunk.js";
|
|
3
|
+
import { chunkTextOutputShape } from "./output-schema.js";
|
|
4
|
+
import { chunkTextInputSchema, chunkTextInputShape, } from "./schemas.js";
|
|
5
|
+
// One numbered section per chunk, heading context in brackets when present, so
|
|
6
|
+
// content[0].text is always scannable without unpacking structuredContent.
|
|
7
|
+
function renderChunkIndex(chunks) {
|
|
8
|
+
if (chunks.length === 0) {
|
|
9
|
+
return '(no chunks emitted — input had no non-whitespace content)';
|
|
10
|
+
}
|
|
11
|
+
return chunks
|
|
12
|
+
.map(chunk => {
|
|
13
|
+
const head = chunk.headingContext ? ` [${chunk.headingContext}]` : '';
|
|
14
|
+
return `## Chunk ${chunk.index}${head}\n\n${chunk.text}`;
|
|
15
|
+
})
|
|
16
|
+
.join('\n\n');
|
|
17
|
+
}
|
|
18
|
+
export function chunkTextDocument(args) {
|
|
19
|
+
const { text, maxTokens, overlap, strategy } = args;
|
|
20
|
+
const chunks = chunkMarkdown(text, { maxTokens, overlap, strategy });
|
|
21
|
+
const content = renderChunkIndex(chunks);
|
|
22
|
+
return {
|
|
23
|
+
content: [{ text: content, type: 'text' }],
|
|
24
|
+
structuredContent: {
|
|
25
|
+
schemaVersion: 1,
|
|
26
|
+
content,
|
|
27
|
+
chunks,
|
|
28
|
+
},
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
export const CHUNK_TEXT_TOOL_DESCRIPTION = `Split already-extracted text into token-bounded chunks for embedding/RAG. Each chunk carries its index, tokenCount (chars/4), and the nearest preceding markdown heading as headingContext. Operates on any text — pair with the \`chunk\` option on \`extract\` when you want chunks inline with the extraction. The server fetches nothing: \`text\` is the only input.`;
|
|
32
|
+
export const chunkTextHandler = tool('chunk_text', chunkTextDocument, chunkTextInputSchema);
|
|
33
|
+
export function registerChunkTextTool(server) {
|
|
34
|
+
return server.registerTool('chunk_text', {
|
|
35
|
+
title: 'Chunk text for RAG/embedding',
|
|
36
|
+
description: CHUNK_TEXT_TOOL_DESCRIPTION,
|
|
37
|
+
inputSchema: chunkTextInputShape,
|
|
38
|
+
outputSchema: chunkTextOutputShape,
|
|
39
|
+
}, chunkTextHandler);
|
|
40
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { Chunk } from '../policy/chunk.ts';
|
|
2
|
+
import type { ToolHandle } from '../server.ts';
|
|
3
|
+
|
|
4
|
+
import { tool } from '../handler.ts';
|
|
5
|
+
import { chunkMarkdown } from '../policy/chunk.ts';
|
|
6
|
+
import { chunkTextOutputShape } from './output-schema.ts';
|
|
7
|
+
import {
|
|
8
|
+
type ChunkTextInput,
|
|
9
|
+
chunkTextInputSchema,
|
|
10
|
+
chunkTextInputShape,
|
|
11
|
+
} from './schemas.ts';
|
|
12
|
+
|
|
13
|
+
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
14
|
+
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
|
|
15
|
+
|
|
16
|
+
// One numbered section per chunk, heading context in brackets when present, so
|
|
17
|
+
// content[0].text is always scannable without unpacking structuredContent.
|
|
18
|
+
function renderChunkIndex(chunks: readonly Chunk[]): string {
|
|
19
|
+
if (chunks.length === 0) {
|
|
20
|
+
return '(no chunks emitted — input had no non-whitespace content)';
|
|
21
|
+
}
|
|
22
|
+
return chunks
|
|
23
|
+
.map(chunk => {
|
|
24
|
+
const head = chunk.headingContext ? ` [${chunk.headingContext}]` : '';
|
|
25
|
+
return `## Chunk ${chunk.index}${head}\n\n${chunk.text}`;
|
|
26
|
+
})
|
|
27
|
+
.join('\n\n');
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function chunkTextDocument(
|
|
31
|
+
args: Readonly<ChunkTextInput>,
|
|
32
|
+
): CallToolResult {
|
|
33
|
+
const { text, maxTokens, overlap, strategy } = args;
|
|
34
|
+
const chunks = chunkMarkdown(text, { maxTokens, overlap, strategy });
|
|
35
|
+
const content = renderChunkIndex(chunks);
|
|
36
|
+
return {
|
|
37
|
+
content: [{ text: content, type: 'text' }],
|
|
38
|
+
structuredContent: {
|
|
39
|
+
schemaVersion: 1,
|
|
40
|
+
content,
|
|
41
|
+
chunks,
|
|
42
|
+
},
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export const CHUNK_TEXT_TOOL_DESCRIPTION = `Split already-extracted text into token-bounded chunks for embedding/RAG. Each chunk carries its index, tokenCount (chars/4), and the nearest preceding markdown heading as headingContext. Operates on any text — pair with the \`chunk\` option on \`extract\` when you want chunks inline with the extraction. The server fetches nothing: \`text\` is the only input.`;
|
|
47
|
+
|
|
48
|
+
export const chunkTextHandler = tool(
|
|
49
|
+
'chunk_text',
|
|
50
|
+
chunkTextDocument,
|
|
51
|
+
chunkTextInputSchema,
|
|
52
|
+
);
|
|
53
|
+
|
|
54
|
+
export function registerChunkTextTool(server: McpServer): ToolHandle {
|
|
55
|
+
return server.registerTool(
|
|
56
|
+
'chunk_text',
|
|
57
|
+
{
|
|
58
|
+
title: 'Chunk text for RAG/embedding',
|
|
59
|
+
description: CHUNK_TEXT_TOOL_DESCRIPTION,
|
|
60
|
+
inputSchema: chunkTextInputShape,
|
|
61
|
+
outputSchema: chunkTextOutputShape,
|
|
62
|
+
},
|
|
63
|
+
chunkTextHandler,
|
|
64
|
+
);
|
|
65
|
+
}
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { tool } from "../handler.js";
|
|
3
|
+
import { buildExplainReport } from "../policy/explain.js";
|
|
4
|
+
import { fromLocalPath, withSchemaDefaults } from "./html-source.js";
|
|
5
|
+
import { localPathField, selectorsSchema, } from "./schemas.js";
|
|
6
|
+
// Schemas live with the tool rather than in schemas.ts/output-schema.ts to keep
|
|
7
|
+
// the explain surface in one file (the report shape is explain-specific and not
|
|
8
|
+
// shared with other tools). `selectorsSchema` is reused verbatim from extract so
|
|
9
|
+
// the two tools agree on the include/exclude contract.
|
|
10
|
+
const explainInputShape = {
|
|
11
|
+
localPath: localPathField,
|
|
12
|
+
baseUrl: z
|
|
13
|
+
.url()
|
|
14
|
+
.describe('Base URL for absolutizing relative links during pagination/gating detection. NEVER fetched — origin context only.')
|
|
15
|
+
.optional(),
|
|
16
|
+
selectors: selectorsSchema,
|
|
17
|
+
topN: z
|
|
18
|
+
.number()
|
|
19
|
+
.int()
|
|
20
|
+
.min(1)
|
|
21
|
+
.max(20)
|
|
22
|
+
.describe('Maximum number of scored candidate nodes to return (highest first). Default 5.')
|
|
23
|
+
.default(5),
|
|
24
|
+
};
|
|
25
|
+
const explainInputSchema = z.object(explainInputShape);
|
|
26
|
+
const candidateSchema = z
|
|
27
|
+
.object({
|
|
28
|
+
className: z
|
|
29
|
+
.string()
|
|
30
|
+
.describe("The candidate's class attribute (raw, unsplit). Empty string when absent."),
|
|
31
|
+
id: z.string().describe("The candidate's id attribute, or empty string."),
|
|
32
|
+
score: z
|
|
33
|
+
.number()
|
|
34
|
+
.describe("Readability's actual contentScore for this node (link-density-scaled). Higher is better; the top entry is Readability's raw top candidate before its parent-walking/only-child adjustments."),
|
|
35
|
+
selector: z
|
|
36
|
+
.string()
|
|
37
|
+
.describe("A CSS-ish hint (tag#id.class1.class2) for locating the node in the host DOM. NOT a unique locator — Readability's score lives on a JS expando invisible to CSS."),
|
|
38
|
+
tag: z
|
|
39
|
+
.string()
|
|
40
|
+
.describe('Uppercase DOM tag name (e.g. "ARTICLE", "MAIN", "DIV").'),
|
|
41
|
+
textLength: z
|
|
42
|
+
.number()
|
|
43
|
+
.int()
|
|
44
|
+
.min(0)
|
|
45
|
+
.describe('Trimmed textContent length of the candidate node, for eyeballing content density.'),
|
|
46
|
+
})
|
|
47
|
+
.describe('One scored candidate node Readability considered, with its real contentScore.');
|
|
48
|
+
const explainOutputShape = {
|
|
49
|
+
schemaVersion: z
|
|
50
|
+
.literal(1)
|
|
51
|
+
.describe('Structured-content schema version. Bumps only on breaking shape changes to this object.'),
|
|
52
|
+
content: z
|
|
53
|
+
.string()
|
|
54
|
+
.describe('Readable rendering of the report (chosen root, ranked candidates, removal counts, gating/pagination, snapshot head) so content[0].text is always scannable.'),
|
|
55
|
+
chosenRoot: candidateSchema
|
|
56
|
+
.nullable()
|
|
57
|
+
.describe('The highest-scoring candidate Readability computed — its raw top pick before parent-walking/only-child post-processing. Null when Readability scored nothing (e.g. empty input).'),
|
|
58
|
+
candidates: z
|
|
59
|
+
.array(candidateSchema)
|
|
60
|
+
.describe("Scored candidate nodes (highest first), capped at topN. These are Readability's real contentScore values, not a self-computed heuristic."),
|
|
61
|
+
readerable: z
|
|
62
|
+
.boolean()
|
|
63
|
+
.describe('Readability isProbablyReaderable verdict on the normalized document.'),
|
|
64
|
+
parseSucceeded: z
|
|
65
|
+
.boolean()
|
|
66
|
+
.describe('True when reader.parse() returned article content. False signals that `extract` would fall back to its selector cascade.'),
|
|
67
|
+
fallbackUsed: z
|
|
68
|
+
.boolean()
|
|
69
|
+
.describe('Always false for explain — this tool runs only the Readability path it is diagnosing, never the fallback cascade.'),
|
|
70
|
+
gating: z
|
|
71
|
+
.object({
|
|
72
|
+
likely: z
|
|
73
|
+
.boolean()
|
|
74
|
+
.describe('True when heuristics strongly suggest the content is paywalled or truncated.'),
|
|
75
|
+
reason: z
|
|
76
|
+
.string()
|
|
77
|
+
.describe('Short label naming the detected signal (e.g. "paywall overlay").'),
|
|
78
|
+
})
|
|
79
|
+
.nullable()
|
|
80
|
+
.describe('Likely paywall / gating signal detected before normalization. Null when none.'),
|
|
81
|
+
pagination: z
|
|
82
|
+
.object({
|
|
83
|
+
type: z
|
|
84
|
+
.enum(['infinite', 'paginated'])
|
|
85
|
+
.describe('Kind of pagination signal detected.'),
|
|
86
|
+
nextUrl: z
|
|
87
|
+
.string()
|
|
88
|
+
.optional()
|
|
89
|
+
.describe('Absolute URL of the detected next page (paginated only). Never fetched.'),
|
|
90
|
+
selector: z
|
|
91
|
+
.string()
|
|
92
|
+
.optional()
|
|
93
|
+
.describe('CSS selector of the load-more / infinite-scroll sentinel (infinite only).'),
|
|
94
|
+
})
|
|
95
|
+
.nullable()
|
|
96
|
+
.describe('Detected pagination / infinite-scroll signal. Null when none.'),
|
|
97
|
+
removedNodes: z
|
|
98
|
+
.object({
|
|
99
|
+
boilerplate: z
|
|
100
|
+
.number()
|
|
101
|
+
.int()
|
|
102
|
+
.min(0)
|
|
103
|
+
.describe('Boilerplate blocks (related-posts, newsletter signup) stripped before Readability.'),
|
|
104
|
+
chrome: z
|
|
105
|
+
.number()
|
|
106
|
+
.int()
|
|
107
|
+
.min(0)
|
|
108
|
+
.describe('Browser-chrome nodes stripped (scrollbars, consent banners, overlays).'),
|
|
109
|
+
total: z
|
|
110
|
+
.number()
|
|
111
|
+
.int()
|
|
112
|
+
.min(0)
|
|
113
|
+
.describe('Net element count removed across the whole pipeline (delta vs. the parsed document).'),
|
|
114
|
+
})
|
|
115
|
+
.describe('Breakdown of nodes removed before Readability saw the document, reused from the extract diagnostics path.'),
|
|
116
|
+
snapshot: z
|
|
117
|
+
.object({
|
|
118
|
+
html: z
|
|
119
|
+
.string()
|
|
120
|
+
.describe('The sanitized-by-normalization (post chrome/boilerplate/script strip) HTML fed to Readability — "what Readability saw". Not DOMPurify-sanitized (that runs on Readability\'s output in `extract`), so it may still carry inline event handlers (`onerror`/`onclick`/…); it is diagnostic data — do not render verbatim.'),
|
|
121
|
+
truncated: z
|
|
122
|
+
.boolean()
|
|
123
|
+
.describe('True when the snapshot was cut at snapshotMaxChars (default 4000).'),
|
|
124
|
+
})
|
|
125
|
+
.describe('Pre-Readability HTML snapshot of the normalized document body.'),
|
|
126
|
+
};
|
|
127
|
+
const explainOutput = z.object(explainOutputShape);
|
|
128
|
+
function formatGating(report) {
|
|
129
|
+
const g = report.gating;
|
|
130
|
+
if (!g) {
|
|
131
|
+
return 'none';
|
|
132
|
+
}
|
|
133
|
+
return `${g.reason}${g.likely ? '' : ' (weak)'}`;
|
|
134
|
+
}
|
|
135
|
+
function formatPagination(report) {
|
|
136
|
+
const p = report.pagination;
|
|
137
|
+
if (!p) {
|
|
138
|
+
return 'none';
|
|
139
|
+
}
|
|
140
|
+
if (p.type === 'paginated') {
|
|
141
|
+
return `paginated -> ${p.nextUrl ?? '(no href)'}`;
|
|
142
|
+
}
|
|
143
|
+
return `infinite (${p.selector ?? 'sentinel'})`;
|
|
144
|
+
}
|
|
145
|
+
function renderText(report) {
|
|
146
|
+
const lines = [];
|
|
147
|
+
const root = report.chosenRoot;
|
|
148
|
+
lines.push(`readerable: ${report.readerable ? 'yes' : 'no'} parse: ${report.parseSucceeded ? 'ok' : 'fail'} fallback: ${report.fallbackUsed ? 'yes' : 'no'}`);
|
|
149
|
+
lines.push(`chosen root: ${root ? `${root.selector} (score ${root.score.toFixed(2)}, ${root.textLength} chars)` : '(no candidate scored)'}`);
|
|
150
|
+
lines.push(`top candidates (${report.candidates.length}):`);
|
|
151
|
+
if (report.candidates.length === 0) {
|
|
152
|
+
lines.push(' (none)');
|
|
153
|
+
}
|
|
154
|
+
report.candidates.forEach((c, i) => {
|
|
155
|
+
lines.push(` ${i + 1}. ${c.selector} score ${c.score.toFixed(2)} (${c.textLength} chars)`);
|
|
156
|
+
});
|
|
157
|
+
const r = report.removedNodes;
|
|
158
|
+
lines.push(`removed: total=${r.total} (chrome=${r.chrome}, boilerplate=${r.boilerplate})`);
|
|
159
|
+
lines.push(`gating: ${formatGating(report)}`);
|
|
160
|
+
lines.push(`pagination: ${formatPagination(report)}`);
|
|
161
|
+
lines.push(`snapshot (${report.snapshot.html.length} chars${report.snapshot.truncated ? ', truncated' : ''}):`);
|
|
162
|
+
lines.push(report.snapshot.html);
|
|
163
|
+
return lines.join('\n');
|
|
164
|
+
}
|
|
165
|
+
export function explainFromHtml(input) {
|
|
166
|
+
const { html, baseUrl, selectors, topN } = withSchemaDefaults(explainInputSchema, input);
|
|
167
|
+
const report = buildExplainReport({
|
|
168
|
+
html,
|
|
169
|
+
selectors,
|
|
170
|
+
topN,
|
|
171
|
+
baseUrl,
|
|
172
|
+
});
|
|
173
|
+
const content = renderText(report);
|
|
174
|
+
return {
|
|
175
|
+
content: [{ text: content, type: 'text' }],
|
|
176
|
+
structuredContent: {
|
|
177
|
+
schemaVersion: 1,
|
|
178
|
+
content,
|
|
179
|
+
chosenRoot: report.chosenRoot,
|
|
180
|
+
candidates: report.candidates,
|
|
181
|
+
readerable: report.readerable,
|
|
182
|
+
parseSucceeded: report.parseSucceeded,
|
|
183
|
+
fallbackUsed: report.fallbackUsed,
|
|
184
|
+
gating: report.gating ?? null,
|
|
185
|
+
pagination: report.pagination ?? null,
|
|
186
|
+
removedNodes: report.removedNodes,
|
|
187
|
+
snapshot: report.snapshot,
|
|
188
|
+
},
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
export const EXPLAIN_TOOL_DESCRIPTION = `Post-mortem diagnostics for extraction: shows WHY Readability picked what it picked. Returns the chosen root, the ranked candidate nodes with their REAL Readability contentScore values (read off the DOM expando Readability stamps during scoring), a categorized removed-nodes breakdown, gating/pagination signals, and a snapshot of the normalized HTML fed to Readability. Runs the same normalize + Readability pipeline as \`extract\` (no fallback cascade, no Turndown). The server fetches nothing: \`localPath\` is the only source, and \`baseUrl\` (optional) is origin context only.`;
|
|
192
|
+
export const explainHandler = tool('explain', input => explainFromHtml(fromLocalPath(input)), explainInputSchema);
|
|
193
|
+
export function registerExplainTool(server) {
|
|
194
|
+
return server.registerTool('explain', {
|
|
195
|
+
title: 'Explain why Readability picked what it picked',
|
|
196
|
+
description: EXPLAIN_TOOL_DESCRIPTION,
|
|
197
|
+
inputSchema: explainInputShape,
|
|
198
|
+
outputSchema: explainOutput,
|
|
199
|
+
}, explainHandler);
|
|
200
|
+
}
|