@cobola/dsh-geo 0.7.0 → 0.9.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/CHANGELOG.md CHANGED
@@ -1,5 +1,56 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.9.0 - 2026-11-29
4
+
5
+ ### Features
6
+
7
+ - Add `generate-llms` and `generate-faq` (CLI) plus `geo_generate_llms` and
8
+ `geo_generate_faq` (MCP): build an llms.txt and FAQPage JSON-LD from the pages
9
+ that were actually crawled.
10
+ - Section extraction now groups each heading with the prose and lists that
11
+ follow it, which both generators read.
12
+
13
+ ### Fixes
14
+
15
+ - The content container is now the largest `<article>`/`<main>` rather than the
16
+ first one. A decorative card placed before the real content used to make a
17
+ content-rich page look like a JavaScript shell (journal123.com scored 79.3
18
+ instead of 71.9 after this fix, because the false "content depends on
19
+ JavaScript" finding disappeared).
20
+
21
+ ### Boundaries
22
+
23
+ - Both generators only extract: llms.txt sections come from real headings and
24
+ anchors, FAQ answers are each section's own prose, and a missing meta
25
+ description is stated rather than invented.
26
+ - A site with no question-shaped heading that has a real answer yields no FAQ
27
+ document (exit code 4) instead of a fabricated one.
28
+ - Both outputs state that Google Search does not use llms.txt, and that Google
29
+ restricted FAQ rich results to authoritative government and health sites in
30
+ August 2023.
31
+
32
+
33
+ ## 0.8.0 - 2026-11-29
34
+
35
+ ### Features
36
+
37
+ - Add a zero-dependency MCP server (`dsh-geo mcp`, plus the `dsh-geo-mcp`
38
+ binary) exposing `geo_scan`, `geo_fix_plan` and `geo_history` over stdio
39
+ JSON-RPC, so MCP clients such as Cursor and Claude Code can audit a workspace
40
+ directly.
41
+ - `geo_scan` over MCP persists reports by default, since the usual next call is
42
+ `geo_fix_plan`, which reads the saved audit.
43
+
44
+ ### Design notes
45
+
46
+ - The stdio transport is implemented directly rather than through the official
47
+ SDK: the protocol surface used here is small, and the SDK brings ~6 MB plus
48
+ express, hono and ajv, which conflicts with the project's auditable,
49
+ minimal-dependency stance.
50
+ - Tool failures return `isError: true` results rather than protocol errors, so a
51
+ model can read the reason and decide what to do next.
52
+
53
+
3
54
  ## 0.7.0 - 2026-11-29
4
55
 
5
56
  ### Features
package/README.md CHANGED
@@ -23,7 +23,8 @@
23
23
  | 会话内结果卡 | 模型调用 `geo_scan` / `geo_fix_plan` 后,对话中直接显示分数、五维、平台参考分与优先修复,不用另开页面 |
24
24
  | `geo_fix_plan`(DSH 工具) | 把最近一次(或指定的)报告变成按影响力排序的修复清单 |
25
25
  | **设置 → GEO 体检**(面板) | 修改抓取页数、robots 策略、限速、超时、体积上限、报告目录、私有目标开关 |
26
- | CLI(`dsh-geo`) | `scan` / `fix-plan` / `history` / `diff`,支持 `--json` 与 `--fail-under`,可直接进 CI |
26
+ | CLI(`dsh-geo`) | `scan` / `ci` / `mcp` / `generate-llms` / `generate-faq` / `fix-plan` / `history` / `diff` |
27
+ | MCP server | `npx -y @cobola/dsh-geo mcp`,给 Cursor / Claude Code 等客户端直接调用 |
27
28
 
28
29
  报告固定在会话工作区的 `.dsh-geo/` 下;报告可能包含页面正文摘录,上传 CI artifact 前请先审阅内容:
29
30
 
@@ -166,7 +167,7 @@ dsh-geo ci https://journal123.com \
166
167
 
167
168
  ```yaml
168
169
  - uses: actions/checkout@v4
169
- - uses: cobola/dsh-geo@v0.7.0
170
+ - uses: cobola/dsh-geo@v0.9.0
170
171
  with:
171
172
  url: https://journal123.com
172
173
  baseline: geo-baseline.json
@@ -200,6 +201,22 @@ CLI 也随 npm 包提供:`npx @cobola/dsh-geo --help`;完整参数见 `dsh-g
200
201
 
201
202
  45 条可审计检查,维度内按权重归一化;`pass` 计 1、`warn` 计 0.5、`fail` 计 0、`skip` 移出分母。总分是五维加权平均。完整规则、阈值与修复建议见 **[docs/RULES.md](docs/RULES.md)**(由 `lib/rules.js` 生成)。
202
203
 
204
+ ### 内容生成器(可选)
205
+
206
+ ```sh
207
+ dsh-geo generate-llms https://journal123.com --out llms.txt
208
+ dsh-geo generate-faq https://journal123.com --out faq.json
209
+ ```
210
+
211
+ 两者都**只从真实抓取的页面里提取**:llms.txt 的分节来自页面真实标题与锚点,FAQ 的答案是那个小节自己的正文。站点没有可用的问句时,不生成 FAQ,退出码 `4`。
212
+
213
+ 需要说清楚的两条平台事实,生成的文件里也会写明:
214
+
215
+ - **Google Search 不使用 llms.txt**,它服务于其他 agent 与工具;
216
+ - **Google 在 2023-08 把 FAQ 富媒体结果限制到权威政府/健康站点**,绝大多数站点已拿不到,这段标记仍合法但不再是富媒体机会。
217
+
218
+ 细节见 [docs/GENERATORS.md](docs/GENERATORS.md)。
219
+
203
220
  ### 平台适配:单独计分,不进 Core 总分
204
221
 
205
222
  | Profile | 状态 | 覆盖内容 |
@@ -241,7 +258,7 @@ fixture 基线(参考时间 `2026-06-15T00:00:00Z`,由测试锁定):
241
258
  ## 开发与发布
242
259
 
243
260
  ```sh
244
- npm test # 运行完整测试套件,验证规则、平台、CI、工具、存储、面板、CLI 与安全边界
261
+ npm test # 运行完整测试套件,验证规则、平台、CI、MCP、工具、存储、面板、CLI 与安全边界
245
262
  npm run docs # 规则改动后重新生成 docs/RULES.md
246
263
  ```
247
264
 
@@ -259,6 +276,11 @@ lib/scan.js 抓取流程
259
276
  lib/rules.js 45 条 Core 规则(唯一事实源)
260
277
  lib/platforms/ 平台 profile(Bing、百度、OpenAI、Perplexity 已实现)
261
278
  lib/ci.js CI 审计、基线与质量门禁
279
+ lib/mcp.js stdio MCP server(零依赖手写 JSON-RPC)
280
+ bin/dsh-geo-mcp.js MCP 二进制入口
281
+ docs/MCP.md MCP 用法与协议行为
282
+ docs/GENERATORS.md 生成器:只提取,不编造
283
+ lib/generate.js llms.txt 与 FAQ JSON-LD 生成器
262
284
  action.yml GitHub composite action
263
285
  lib/score.js 评分聚合(纯函数)
264
286
  lib/report.js 报告/修复清单/diff 生成
@@ -0,0 +1,31 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * MCP server entry point.
4
+ *
5
+ * Register it with any MCP client (Cursor, Claude Code, …):
6
+ *
7
+ * { "command": "npx", "args": ["-y", "@cobola/dsh-geo", "mcp"] }
8
+ *
9
+ * Reports are written to `<cwd>/.dsh-geo/`, so run the client in the workspace
10
+ * you want audited.
11
+ */
12
+ import path from 'node:path';
13
+
14
+ import { serve } from '../lib/mcp.js';
15
+
16
+ const log = (text) => process.stderr.write(`${text}\n`);
17
+
18
+ serve({
19
+ input: process.stdin,
20
+ output: process.stdout,
21
+ cwd: process.cwd(),
22
+ log,
23
+ }).then(
24
+ () => { process.exitCode = 0; },
25
+ (error) => {
26
+ log(`dsh-geo mcp: ${error && error.message ? error.message : String(error)}`);
27
+ process.exitCode = 1;
28
+ },
29
+ );
30
+
31
+ log(`dsh-geo mcp: serving stdio in ${path.resolve(process.cwd())}`);
package/bin/dsh-geo.js CHANGED
@@ -26,11 +26,28 @@ const HELP = `dsh-geo ${version} — deterministic GEO/SEO audit
26
26
  Usage:
27
27
  dsh-geo scan <url> [options]
28
28
  dsh-geo ci <url> [options]
29
+ dsh-geo mcp Serve the Model Context Protocol over stdio.
30
+ dsh-geo generate-llms <url> [--out <path>]
31
+ dsh-geo generate-faq <url> [--out <path>]
29
32
  dsh-geo fix-plan [options]
30
33
  dsh-geo history [options]
31
34
  dsh-geo diff <before.json> <after.json> [--json]
32
35
  dsh-geo --help | --version
33
36
 
37
+ mcp:
38
+ Runs an MCP stdio server exposing geo_scan, geo_fix_plan and geo_history.
39
+ Register it in an MCP client as: npx -y @cobola/dsh-geo mcp
40
+ Reports are written to <cwd>/.dsh-geo/ for the directory you start it in.
41
+
42
+ generate-llms / generate-faq:
43
+ Build content from the pages that were actually crawled. Nothing is invented:
44
+ llms.txt sections come from real headings, and FAQ answers are each
45
+ section's own prose. Google Search does not use llms.txt, and FAQ rich
46
+ results have been limited to authoritative government and health sites since
47
+ August 2023; both outputs say so in their own text.
48
+ Exit code 4 when a FAQ document cannot be built because the site has no
49
+ question-shaped heading with a real answer.
50
+
34
51
  ci options (for CI jobs):
35
52
  --baseline <path> Compare against a committed baseline report.
36
53
  --fail-under <score> Exit 3 when the total is below this score.
@@ -94,6 +111,7 @@ function defaults() {
94
111
  jsonFile: null,
95
112
  reportFile: null,
96
113
  baselineOut: null,
114
+ out: null,
97
115
  };
98
116
  }
99
117
 
@@ -101,6 +119,7 @@ const VALUE_OPTIONS = new Set([
101
119
  'dir', 'fail-under', 'max-pages', 'now', 'timeout', 'rate-limit',
102
120
  'user-agent', 'report', 'limit',
103
121
  'baseline', 'max-regression', 'summary-file', 'json-file', 'report-file', 'write-baseline',
122
+ 'out',
104
123
  ]);
105
124
 
106
125
  function parseArgs(argv) {
@@ -148,6 +167,7 @@ function parseArgs(argv) {
148
167
  case 'json-file': options.jsonFile = value; break;
149
168
  case 'report-file': options.reportFile = value; break;
150
169
  case 'write-baseline': options.baselineOut = value; break;
170
+ case 'out': options.out = value; break;
151
171
  default: throw new Error(`Unknown option: --${key}`);
152
172
  }
153
173
  }
@@ -163,7 +183,7 @@ function validate(options, commandName) {
163
183
  }
164
184
  if (options.now !== null && !Number.isFinite(Date.parse(options.now))) throw new Error(`--now is not a valid ISO time: ${options.now}`);
165
185
  if (!Number.isInteger(options.limit) || options.limit < 1) throw new Error('--limit must be a positive integer');
166
- if (!['scan', 'ci'].includes(commandName) && (options.maxPages !== 6 || options.now !== null || !options.respectRobots
186
+ if (!['scan', 'ci', 'generate-llms', 'generate-faq'].includes(commandName) && (options.maxPages !== 6 || options.now !== null || !options.respectRobots
167
187
  || options.allowPrivate || options.insecureTls || options.timeoutMs !== 10_000 || options.rateLimitMs !== 250)) {
168
188
  throw new Error(`Scan-only options are not accepted by "${commandName}"`);
169
189
  }
@@ -390,9 +410,72 @@ async function commandCi(positionals, options) {
390
410
  return result.exitCode;
391
411
  }
392
412
 
413
+ async function commandMcp(positionals, options) {
414
+ if (positionals.length > 0) throw new Error(`Unexpected argument: ${positionals[0]}`);
415
+ const { serve } = await import('../lib/mcp.js');
416
+ await serve({
417
+ input: process.stdin,
418
+ output: process.stdout,
419
+ cwd: process.cwd(),
420
+ log: (text) => process.stderr.write(`${text}\n`),
421
+ });
422
+ return 0;
423
+ }
424
+
425
+ async function commandGenerate(positionals, options) {
426
+ const kind = options.generateKind;
427
+ if (kind !== 'llms' && kind !== 'faq') throw new Error(`Unknown generator: ${kind}`);
428
+ const url = positionals[0];
429
+ if (!url) throw new Error('Missing <url>');
430
+
431
+ const { auditSite } = await import('../lib/audit.js');
432
+ const { generateLlmsTxt, generateFaqJsonLd, FAQ_NOTE } = await import('../lib/generate.js');
433
+ const { scan } = await auditSite(url, {
434
+ maxPages: options.maxPages,
435
+ respectRobots: options.respectRobots,
436
+ allowPrivate: options.allowPrivate,
437
+ insecureTls: options.insecureTls,
438
+ timeoutMs: options.timeoutMs,
439
+ rateLimitMs: options.rateLimitMs,
440
+ userAgent: options.userAgent,
441
+ now: options.now ?? undefined,
442
+ });
443
+
444
+ if (kind === 'llms') {
445
+ const result = generateLlmsTxt(scan);
446
+ if (options.out) {
447
+ await fs.mkdir(path.dirname(path.resolve(options.out)), { recursive: true });
448
+ await fs.writeFile(path.resolve(options.out), result.content, 'utf8');
449
+ process.stderr.write(`dsh-geo: wrote ${options.out} (${result.links} links from ${result.sourcePages} page(s))\n`);
450
+ } else {
451
+ process.stdout.write(result.content);
452
+ }
453
+ return 0;
454
+ }
455
+
456
+ const result = generateFaqJsonLd(scan);
457
+ if (!result.json) {
458
+ process.stderr.write(`dsh-geo: ${result.skipped}\n`);
459
+ return 4;
460
+ }
461
+ const output = `${JSON.stringify(result.json, null, 2)}\n`;
462
+ process.stderr.write(`dsh-geo: ${FAQ_NOTE}\n`);
463
+ if (options.out) {
464
+ await fs.mkdir(path.dirname(path.resolve(options.out)), { recursive: true });
465
+ await fs.writeFile(path.resolve(options.out), output, 'utf8');
466
+ process.stderr.write(`dsh-geo: wrote ${options.out} (${result.items.length} item(s))\n`);
467
+ } else {
468
+ process.stdout.write(output);
469
+ }
470
+ return 0;
471
+ }
472
+
393
473
  const COMMANDS = {
394
474
  scan: commandScan,
395
475
  ci: commandCi,
476
+ mcp: commandMcp,
477
+ 'generate-llms': (pos, opts) => commandGenerate(pos, { ...opts, generateKind: 'llms' }),
478
+ 'generate-faq': (pos, opts) => commandGenerate(pos, { ...opts, generateKind: 'faq' }),
396
479
  'fix-plan': commandFixPlan,
397
480
  history: commandHistory,
398
481
  diff: commandDiff,
@@ -428,7 +511,7 @@ async function main(argv) {
428
511
  validate(parsed.options, name);
429
512
  return await handler(positionals, parsed.options);
430
513
  } catch (error) {
431
- const usageError = /Missing <url>|Unexpected argument|Scan-only options|diff needs exactly/.test(error.message);
514
+ const usageError = /Missing <url>|Unexpected argument|Scan-only options|diff needs exactly|Unknown generator/.test(error.message);
432
515
  process.stderr.write(`dsh-geo: ${error.message}\n`);
433
516
  return usageError ? 2 : 1;
434
517
  }
package/docs/CI.md CHANGED
@@ -123,7 +123,7 @@ on:
123
123
 
124
124
  ```yaml
125
125
  - uses: actions/checkout@v4
126
- - uses: cobola/dsh-geo@v0.7.0
126
+ - uses: cobola/dsh-geo@v0.9.0
127
127
  with:
128
128
  url: https://journal123.com
129
129
  baseline: geo-baseline.json
@@ -0,0 +1,75 @@
1
+ # 内容生成器
2
+
3
+ 两个生成器:`generate-llms` 与 `generate-faq`。它们从**实际抓取到的页面**里提取内容,不编造。
4
+
5
+ ```sh
6
+ dsh-geo generate-llms https://journal123.com --out llms.txt
7
+ dsh-geo generate-faq https://journal123.com --out faq.json
8
+ ```
9
+
10
+ 也可以在 MCP 里调用:`geo_generate_llms`、`geo_generate_faq`。
11
+
12
+ ## 为什么不编造
13
+
14
+ 生成器的诱惑是“看起来内容更完整”:补一段摘要、凑几条 FAQ。但这个工具的整个前提是**证据可追溯**。如果生成器输出了站点上不存在的文字,那就是在向模型misrepresent 一个站点——这正好是我们在审计里批评的行为。
15
+
16
+ 所以两个生成器都只做提取:
17
+
18
+ - **llms.txt 的分节**来自页面真实存在的 `<h2>`/`<h3>`,带真实 `id` 锚点;
19
+ - **FAQ 的答案**是那个小节自己的正文,不是重写的;
20
+ - 页面没有 meta description 时,输出会**明确说明缺失**,而不是编一句;
21
+ - 站点没有“问句式标题 + 真实答案”时,**不生成 FAQ 文档**,退出码 `4`。
22
+
23
+ ## llms.txt
24
+
25
+ 结构:
26
+
27
+ ```text
28
+ # <站点名>
29
+
30
+ > <入口页的 meta description;没有就说明缺失>
31
+
32
+ Note: Google Search does not use this file. ...
33
+
34
+ ## Pages
35
+ - [页面标题](URL)
36
+
37
+ ## Sections
38
+ - [真实标题](URL#anchor) — 该小节正文摘录
39
+
40
+ ## Machine-readable resources
41
+ - [sitemap](URL)
42
+ - [robots.txt](URL)
43
+ ```
44
+
45
+ **重要**:Google Search 明确不使用 `llms.txt`。它服务于其他选择读取它的 agent 与工具。这句话写在生成的文件里,不只是文档里。
46
+
47
+ ## FAQ JSON-LD
48
+
49
+ ```json
50
+ {
51
+ "@context": "https://schema.org",
52
+ "@type": "FAQPage",
53
+ "mainEntity": [
54
+ { "@type": "Question", "name": "...", "acceptedAnswer": { "@type": "Answer", "text": "..." } }
55
+ ]
56
+ }
57
+ ```
58
+
59
+ **重要**:Google 在 2023-08 把 FAQ 富媒体搜索结果限制到权威政府与健康站点,绝大多数站点已不再获得该富媒体结果。这段标记仍然合法、是机器可读结构,但**不是富媒体机会**。这句话同样写在输出里。
60
+
61
+ 参考:[Google: HowTo 和常见问题解答富媒体搜索结果方面的变化](https://developers.google.com/search/blog/2023/08/howto-faq-changes)
62
+
63
+ ## 边界
64
+
65
+ - 生成器**不修改站点**,只输出文本或 JSON;
66
+ - 不发布、不写入站点仓库,你自己决定放哪里;
67
+ - 不生成内容、不扩充内容、不做“改写优化”;
68
+ - 产物需要人工审阅后再上线。
69
+
70
+ ## 退出码
71
+
72
+ | 码 | 含义 |
73
+ |---|---|
74
+ | 0 | 生成成功 |
75
+ | 4 | 无法生成 FAQ(站点没有可用的问句标题与答案) |
package/docs/MCP.md ADDED
@@ -0,0 +1,67 @@
1
+ # 用 MCP 客户端调用 dsh-geo
2
+
3
+ `dsh-geo` 自带一个 stdio MCP server,Cursor、Claude Code 等支持 MCP 的客户端可以直接调用它的工具。
4
+
5
+ ## 为什么不用官方 SDK
6
+
7
+ MCP 的 stdio 传输就是 stdin/stdout 上的换行分隔 JSON-RPC 2.0。官方 `@modelcontextprotocol/sdk` 约 6 MB,还带 express、hono、ajv 等依赖。这个项目的原则是最小依赖、每一行可审计,所以 server 是手写的([lib/mcp.js](../lib/mcp.js)),零新增依赖。
8
+
9
+ ## 注册
10
+
11
+ ```json
12
+ {
13
+ "mcpServers": {
14
+ "dsh-geo": {
15
+ "command": "npx",
16
+ "args": ["-y", "@cobola/dsh-geo", "mcp"]
17
+ }
18
+ }
19
+ }
20
+ ```
21
+
22
+ 或全局安装后用二进制:
23
+
24
+ ```sh
25
+ npm install -g @cobola/dsh-geo
26
+ dsh-geo-mcp
27
+ ```
28
+
29
+ 报告写入**启动目录**下的 `.dsh-geo/`,所以请在你要体检的工作区里启动客户端。
30
+
31
+ ## 提供的工具
32
+
33
+ | 工具 | 作用 |
34
+ |---|---|
35
+ | `geo_scan` | 审计一个站点,返回分数、五维、平台参考分与优先修复 |
36
+ | `geo_fix_plan` | 把最近一次审计变成有序修复清单,写入 `.dsh-geo/` |
37
+ | `geo_history` | 列出本工作区最近的审计记录 |
38
+
39
+ `geo_scan` 默认落盘(`save: false` 可关),因为客户端下一步通常就是 `geo_fix_plan`,它需要读持久化的报告。
40
+
41
+ ## 协议行为
42
+
43
+ - init、`tools/list`、`tools/call`、`ping` 全部实现;
44
+ - 通知(无 `id`)永不回应;
45
+ - 未知方法返回 `-32601`,参数错误返回 `-32602`;
46
+ - **工具执行失败是一个 `isError: true` 的结果,不是协议错误**——模型需要读到失败原因再决定下一步;
47
+ - stdout 只走协议消息,日志全部走 stderr。
48
+
49
+ ## 安全边界
50
+
51
+ MCP server 沿用引擎的默认策略:
52
+
53
+ - 只允许公网 http(s);
54
+ - 拒绝回环、私网、CGNAT、NAT64/6to4/Teredo 与云元数据地址;
55
+ - 默认遵守 robots.txt;
56
+ - 限额 6 页 / 1.5 MB / 10 秒 / 同主机 250 ms。
57
+
58
+ `allowPrivate` 与 `insecureTls` 只存在于测试上下文,stdio server 不会开启它们——外部 MCP 客户端无法借此访问你的内网。
59
+
60
+ ## 它不做什么
61
+
62
+ - 不测排名、流量或 AI 引用;
63
+ - 不修改被审计的站点;
64
+ - 不执行 JavaScript;
65
+ - 不保证任何平台会引用你的页面。
66
+
67
+ 平台分(Bing、百度、OpenAI、Perplexity)单独展示,且每个 profile 都写明该平台哪些规则没有公开。
package/docs/index.json CHANGED
@@ -27,7 +27,7 @@
27
27
  },
28
28
  "versions": [
29
29
  {
30
- "version": "0.7.0",
30
+ "version": "0.9.0",
31
31
  "source": {
32
32
  "type": "npm"
33
33
  },
@@ -23,7 +23,7 @@ jobs:
23
23
  - uses: actions/checkout@v4
24
24
 
25
25
  - name: Audit and compare against the committed baseline
26
- uses: cobola/dsh-geo@v0.7.0
26
+ uses: cobola/dsh-geo@v0.9.0
27
27
  with:
28
28
  url: https://journal123.com
29
29
  baseline: geo-baseline.json
@@ -15,7 +15,7 @@ jobs:
15
15
  - uses: actions/checkout@v4
16
16
 
17
17
  - name: Audit and write a baseline
18
- uses: cobola/dsh-geo@v0.7.0
18
+ uses: cobola/dsh-geo@v0.9.0
19
19
  with:
20
20
  url: https://journal123.com
21
21
  now: 2026-11-29T00:00:00Z
@@ -0,0 +1,178 @@
1
+ /**
2
+ * Content generators: llms.txt and FAQPage JSON-LD.
3
+ *
4
+ * Both generate from what the audited pages actually contain. Nothing here
5
+ * invents a section, a question, or an answer: a generator that produced text
6
+ * the site does not have would be a way to misrepresent a site to a model, and
7
+ * the audit's whole premise is that evidence must be traceable.
8
+ *
9
+ * Honest scoping, stated in the output itself:
10
+ * - Google Search does not use llms.txt. It is useful for other agents and
11
+ * tools; it is not a Google ranking mechanism.
12
+ * - Google restricted FAQ rich results to authoritative government and health
13
+ * sites in August 2023, so FAQPage markup no longer earns rich results for
14
+ * most sites. It is still valid, machine-readable structure; it is not a
15
+ * rich-result opportunity.
16
+ */
17
+
18
+ const QUESTION_START = /^(?:how|what|why|when|where|who|which|can|should|do|does|is|are|will)\b|^(?:如何|为何|为什么|怎么|怎样|什么|哪些|哪个|是否|能否)/i;
19
+
20
+ const LLMS_NOTE = 'Note: Google Search does not use this file. It is published for other AI agents and tools that choose to read it.';
21
+ const FAQ_NOTE = 'Note: Google restricted FAQ rich results to authoritative government and health sites in August 2023, so this markup does not earn rich results for most sites. It remains valid, machine-readable structure.';
22
+
23
+ function trimSlash(value) {
24
+ const url = new URL(value);
25
+ url.hash = '';
26
+ let path = url.pathname;
27
+ if (path.length > 1 && path.endsWith('/')) path = path.slice(0, -1);
28
+ return `${url.origin}${path}${url.search}`;
29
+ }
30
+
31
+ function siteName(scan) {
32
+ try {
33
+ const host = new URL(scan.startUrl).hostname.replace(/^\.?www\./, '');
34
+ return host;
35
+ } catch {
36
+ return 'site';
37
+ }
38
+ }
39
+
40
+ function pageTitle(page) {
41
+ const title = page.facts?.title ?? '';
42
+ return title.length > 0 ? title : page.path;
43
+ }
44
+
45
+ function isQuestion(heading) {
46
+ return QUESTION_START.test(heading) || /[??]\s*$/.test(heading);
47
+ }
48
+
49
+ function firstAnswer(section, maxLength = 320) {
50
+ const text = (section.paragraphs ?? []).join(' ').trim();
51
+ if (text.length === 0) return '';
52
+ return text.length > maxLength ? `${text.slice(0, maxLength)}…` : text;
53
+ }
54
+
55
+ /**
56
+ * Build an llms.txt from the audited pages.
57
+ *
58
+ * @param {object} scan - Scan artifact.
59
+ * @param {{maxLinks?: number}} [options]
60
+ * @returns {{content: string, sections: number, links: number, sourcePages: number}}
61
+ */
62
+ export function generateLlmsTxt(scan, options = {}) {
63
+ const maxLinks = options.maxLinks ?? 60;
64
+ const pages = (scan.pages ?? []).filter((page) => page.facts && page.status === 200);
65
+ const lines = [];
66
+ const name = siteName(scan);
67
+
68
+ lines.push(`# ${name}`);
69
+ lines.push('');
70
+ const primary = pages.find((page) => page.depth === 0) ?? pages[0];
71
+ const description = primary?.facts?.description ?? '';
72
+ if (description) {
73
+ lines.push(`> ${description}`);
74
+ } else {
75
+ // Never invent a summary; state the absence instead.
76
+ lines.push(`> ${name} — generated index. No meta description was found on the entry page, so no summary is provided.`);
77
+ }
78
+ lines.push('');
79
+ lines.push(LLMS_NOTE);
80
+ lines.push('');
81
+
82
+ // Core pages: the entry page plus every crawled page that carries real content.
83
+ const withContent = pages.filter((page) => (page.facts.contentLength ?? page.facts.textLength) >= 200);
84
+ const core = (withContent.length > 0 ? withContent : pages).slice(0, maxLinks);
85
+
86
+ lines.push('## Pages');
87
+ lines.push('');
88
+ for (const page of core) {
89
+ lines.push(`- [${pageTitle(page)}](${trimSlash(page.url)})`);
90
+ }
91
+ if (pages.length > core.length) {
92
+ lines.push(`- … ${pages.length - core.length} more page(s) were crawled but not listed`);
93
+ }
94
+ lines.push('');
95
+
96
+ // Section-level index from the entry page: real headings only.
97
+ if (primary && (primary.facts.sections ?? []).length > 0) {
98
+ const headings = primary.facts.sections.filter((section) => section.level >= 2 && section.heading.length > 0);
99
+ if (headings.length > 0) {
100
+ lines.push('## Sections');
101
+ lines.push('');
102
+ for (const section of headings.slice(0, maxLinks)) {
103
+ const anchor = section.id ? `${trimSlash(primary.url)}#${section.id}` : trimSlash(primary.url);
104
+ const answer = firstAnswer(section, 160);
105
+ lines.push(`- [${section.heading}](${anchor})${answer ? ` — ${answer}` : ''}`);
106
+ }
107
+ lines.push('');
108
+ }
109
+ }
110
+
111
+ const sitemap = scan.sitemap?.valid ? scan.sitemap.url : null;
112
+ lines.push('## Machine-readable resources');
113
+ lines.push('');
114
+ if (sitemap) lines.push(`- [sitemap](${trimSlash(sitemap)})`);
115
+ lines.push(`- [robots.txt](${trimSlash(new URL('/robots.txt', scan.origin).href)})`);
116
+ lines.push('');
117
+
118
+ const content = `${lines.join('\n').trimEnd()}\n`;
119
+ return {
120
+ content,
121
+ sections: (content.match(/^## /gm) ?? []).length,
122
+ links: (content.match(/^- \[/gm) ?? []).length,
123
+ sourcePages: core.length,
124
+ };
125
+ }
126
+
127
+ /**
128
+ * Build FAQPage JSON-LD from question-shaped headings that have a real answer.
129
+ *
130
+ * Only headings that already exist on a crawled page are used, and each answer
131
+ * is that section's own prose. A site with no question headings yields no
132
+ * document at all rather than a fabricated FAQ.
133
+ *
134
+ * @param {object} scan - Scan artifact.
135
+ * @param {{maxItems?: number}} [options]
136
+ * @returns {{json: object|null, items: Array<{question: string, answer: string, url: string}>, skipped: string|null}}
137
+ */
138
+ export function generateFaqJsonLd(scan, options = {}) {
139
+ const maxItems = options.maxItems ?? 20;
140
+ const pages = (scan.pages ?? []).filter((page) => page.facts && page.status === 200);
141
+ const items = [];
142
+
143
+ for (const page of pages) {
144
+ for (const section of page.facts.sections ?? []) {
145
+ if (items.length >= maxItems) break;
146
+ if (!isQuestion(section.heading)) continue;
147
+ const answer = firstAnswer(section, 600);
148
+ // A question with no prose is not an FAQ entry; the answer must exist.
149
+ if (answer.length < 30) continue;
150
+ items.push({ question: section.heading, answer, url: trimSlash(page.url) });
151
+ }
152
+ if (items.length >= maxItems) break;
153
+ }
154
+
155
+ if (items.length === 0) {
156
+ return {
157
+ json: null,
158
+ items: [],
159
+ skipped: 'No question-shaped heading with a real answer was found, so no FAQPage document was generated.',
160
+ };
161
+ }
162
+
163
+ return {
164
+ json: {
165
+ '@context': 'https://schema.org',
166
+ '@type': 'FAQPage',
167
+ mainEntity: items.map((item) => ({
168
+ '@type': 'Question',
169
+ name: item.question,
170
+ acceptedAnswer: { '@type': 'Answer', text: item.answer },
171
+ })),
172
+ },
173
+ items,
174
+ skipped: null,
175
+ };
176
+ }
177
+
178
+ export { LLMS_NOTE, FAQ_NOTE, isQuestion };
package/lib/html.js CHANGED
@@ -434,6 +434,11 @@ export function analyzeHtml(html, pageUrl) {
434
434
  const paragraphs = [];
435
435
  const snippetCandidates = [];
436
436
  const headingIds = [];
437
+ // Sections group a heading with the prose that follows it. They are what the
438
+ // llms.txt and FAQ generators read: both must be able to quote the page, never
439
+ // invent content it does not contain.
440
+ const sections = [];
441
+ let currentSection = null;
437
442
  let pendingHeading = null;
438
443
  for (const node of nodes) {
439
444
  const level = HEADING_LEVEL[node.tag];
@@ -446,6 +451,8 @@ export function analyzeHtml(html, pageUrl) {
446
451
  if (id) headingIds.push(id);
447
452
  lastHeading = level;
448
453
  pendingHeading = headingText;
454
+ currentSection = { level, heading: headingText.slice(0, 300), id, paragraphs: [] };
455
+ sections.push(currentSection);
449
456
  continue;
450
457
  }
451
458
  if (node.tag === 'p') {
@@ -454,19 +461,42 @@ export function analyzeHtml(html, pageUrl) {
454
461
  if (!text) continue;
455
462
  const words = countWords(text);
456
463
  paragraphs.push({ text: text.slice(0, 1000), words, afterHeading: lastHeading });
464
+ if (currentSection) currentSection.paragraphs.push(text.slice(0, 1000));
457
465
  if (pendingHeading !== null && words >= 30 && words <= 140) {
458
466
  snippetCandidates.push({ heading: pendingHeading.slice(0, 200), words });
459
467
  }
460
468
  pendingHeading = null;
461
469
  }
470
+ // A list or table directly under a heading carries answers too.
471
+ if (currentSection && (node.tag === 'ul' || node.tag === 'ol' || node.tag === 'dl' || node.tag === 'table')) {
472
+ const blockText = textOf(node);
473
+ if (blockText) currentSection.paragraphs.push(blockText.slice(0, 1000));
474
+ }
462
475
  }
463
476
 
464
477
  const bodyText = textOf(body ?? doc);
465
- const contentRoot = findFirst(doc, (node) => node.tag === 'article')
466
- ?? findFirst(doc, (node) => node.tag === 'main')
467
- ?? body
468
- ?? doc;
469
- const contentText = textOf(contentRoot);
478
+
479
+ // Picking the first <article>/<main> is wrong on real pages: a card or a
480
+ // decorative wrapper often comes first, which makes a content-rich page look
481
+ // like a JavaScript shell. Take the largest candidate instead, and fall back
482
+ // to the body when no semantic container actually holds the content.
483
+ const containers = [];
484
+ walk(doc, (node) => {
485
+ if (node.tag === 'article' || node.tag === 'main') containers.push(node);
486
+ });
487
+ let contentRoot = null;
488
+ let contentText = '';
489
+ for (const candidate of containers) {
490
+ const text = textOf(candidate);
491
+ if (text.length > contentText.length) {
492
+ contentText = text;
493
+ contentRoot = candidate;
494
+ }
495
+ }
496
+ if (contentText.length < bodyText.length * 0.5) {
497
+ contentRoot = body ?? doc;
498
+ contentText = bodyText;
499
+ }
470
500
  const noscriptText = nodes
471
501
  .filter((node) => node.tag === 'noscript')
472
502
  .map((node) => textOf(node))
@@ -638,6 +668,7 @@ export function analyzeHtml(html, pageUrl) {
638
668
  dataNosnippetCount: nodes.filter((node) => node.attrs && 'data-nosnippet' in node.attrs).length,
639
669
  metaBingbot: (meta.bingbot ?? '').toLowerCase(),
640
670
  questionHeadings,
671
+ sections: sections.filter((section) => section.heading.length > 0),
641
672
  snippetBlockCount: snippetCandidates.length,
642
673
  // A shell has scripts but no readable structure at all. This is a
643
674
  // diagnostic; rules score the actual text length and heading structure.
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Model-facing text for one audit.
3
+ *
4
+ * An MCP client shows this text to a model, so it has to be compact, factual
5
+ * and explicit about what the numbers mean. The same facts also exist as JSON
6
+ * in `.dsh-geo/latest.json` for anything that wants to parse them.
7
+ */
8
+ const STATUS_LABEL = {
9
+ pass: 'pass',
10
+ warn: 'partial',
11
+ fail: 'fail',
12
+ skip: 'n/a',
13
+ };
14
+
15
+ /**
16
+ * @param {object} scan - Scan artifact.
17
+ * @param {object} report - Score report.
18
+ * @returns {string} Markdown-ish plain text for a model.
19
+ */
20
+ export function summariseScanForModel(scan, report) {
21
+ const lines = [];
22
+ lines.push(`Website visibility audit — ${scan.startUrl}`);
23
+ lines.push(`Score: ${report.total}/100 (${report.grade} ${report.gradeLabel}) across ${scan.stats.pages} page(s)`);
24
+ lines.push(`Checks: ${report.counts.pass} pass / ${report.counts.warn} partial / ${report.counts.fail} fail / ${report.counts.skip} n/a`);
25
+ lines.push('');
26
+
27
+ lines.push('Dimensions:');
28
+ for (const dimension of report.dimensions) {
29
+ lines.push(`- ${dimension.title}: ${dimension.score} (weight ${dimension.weight})`);
30
+ }
31
+ lines.push('');
32
+
33
+ const platforms = report.platforms ?? [];
34
+ if (platforms.length > 0) {
35
+ lines.push('Platform reference scores (these do NOT contribute to the score above):');
36
+ for (const platform of platforms) {
37
+ lines.push(`- ${platform.title}: ${platform.total}`);
38
+ }
39
+ for (const platform of platforms) {
40
+ if (platform.limitation) lines.push(` note (${platform.title}): ${platform.limitation}`);
41
+ }
42
+ lines.push('');
43
+ }
44
+
45
+ if (report.blockedByRobots) {
46
+ lines.push('robots.txt refused this audit, so no pages were fetched. Fix robots or get owner approval before re-running.');
47
+ lines.push('');
48
+ }
49
+
50
+ if (report.actions.length > 0) {
51
+ lines.push('Failures and partial results, highest impact first:');
52
+ report.actions.forEach((action, index) => {
53
+ lines.push(`${index + 1}. [${action.dimensionTitle} ${action.weight}] ${action.title} — ${action.evidence}`);
54
+ lines.push(` fix: ${action.fix}`);
55
+ });
56
+ } else {
57
+ lines.push('Every check passed.');
58
+ }
59
+ lines.push('');
60
+
61
+ const failing = report.findings.filter((finding) => finding.status === 'fail' || finding.status === 'warn');
62
+ if (failing.length > report.actions.length) {
63
+ lines.push(`(${failing.length - report.actions.length} more checks need attention; see .dsh-geo/latest.json)`);
64
+ lines.push('');
65
+ }
66
+
67
+ lines.push('This is a readiness report on crawlable structure. It does not measure rankings, traffic, or whether any AI product cites the page.');
68
+ return lines.join('\n');
69
+ }
70
+
71
+ export { STATUS_LABEL };
package/lib/mcp.js ADDED
@@ -0,0 +1,352 @@
1
+ /**
2
+ * Minimal MCP server over stdio.
3
+ *
4
+ * The Model Context Protocol's stdio transport is newline-delimited JSON-RPC
5
+ * 2.0 on stdin/stdout, so a server needs no SDK: the handshake, tool listing and
6
+ * tool calls are a handful of methods. Implementing them here keeps the package
7
+ * dependency-free and every line auditable, which matches the rest of the
8
+ * project — a 6 MB SDK with express and hono would not.
9
+ *
10
+ * Protocol notes that matter for correctness:
11
+ * - stdout carries protocol messages only; logs and errors go to stderr, or
12
+ * they corrupt the stream.
13
+ * - an initialize request must be answered before any other request.
14
+ * - a notification has no `id` and must never be answered.
15
+ * - unknown tools and bad arguments are reported as tool results with
16
+ * `isError: true`, not as protocol errors; protocol errors are for malformed
17
+ * JSON-RPC envelopes.
18
+ */
19
+ import { auditSite, persistAudit, planFromReport } from './audit.js';
20
+ import { summariseScanForModel } from './mcp-summary.js';
21
+
22
+ export const PROTOCOL_VERSION = '2024-11-05';
23
+ export const SERVER_INFO = { name: 'dsh-geo', version: '1.0.0' };
24
+
25
+ const PARSE_ERROR = -32700;
26
+ const INVALID_REQUEST = -32600;
27
+ const METHOD_NOT_FOUND = -32601;
28
+ const INVALID_PARAMS = -32602;
29
+ const INTERNAL_ERROR = -32603;
30
+
31
+ /** Tool definitions advertised to the client. */
32
+ export const MCP_TOOLS = [
33
+ {
34
+ name: 'geo_scan',
35
+ description:
36
+ 'Audit a public website for GEO/SEO readiness. Fetches raw HTML only, honors robots.txt by default, refuses private and cloud-metadata destinations, and rate-limits requests. Returns a reproducible score with evidence across five dimensions plus platform reference scores and prioritized fixes. It never edits the site or measures rankings, traffic or AI citations.',
37
+ inputSchema: {
38
+ type: 'object',
39
+ properties: {
40
+ url: { type: 'string', description: 'Absolute http(s) URL of the site entry page.' },
41
+ max_pages: { type: 'integer', minimum: 1, maximum: 50, description: 'Pages to crawl (default 6).' },
42
+ now: { type: 'string', description: 'ISO-8601 reference time for freshness checks. Reuse one value across runs so results stay comparable.' },
43
+ save: { type: 'boolean', description: 'Write reports into the workspace .dsh-geo/ directory (default true).' },
44
+ },
45
+ required: ['url'],
46
+ },
47
+ },
48
+ {
49
+ name: 'geo_fix_plan',
50
+ description:
51
+ 'Turn the latest saved audit into an ordered repair plan. Writes fix-plan.md and fix-plan.json into the workspace .dsh-geo/ directory. It does not change the site; apply the fixes in your own workflow and re-run geo_scan to verify.',
52
+ inputSchema: {
53
+ type: 'object',
54
+ properties: {
55
+ report_path: { type: 'string', description: 'Path to a saved report inside the workspace. Defaults to the newest audit.' },
56
+ },
57
+ },
58
+ },
59
+ {
60
+ name: 'geo_generate_llms',
61
+ description:
62
+ 'Build an llms.txt from the pages that were actually crawled: the page list and section index come from real headings, and nothing is invented. Google Search does not use llms.txt; the generated file says so. A generator, not a fix: review the output before publishing it.',
63
+ inputSchema: {
64
+ type: 'object',
65
+ properties: {
66
+ url: { type: 'string', description: 'Absolute http(s) URL of the site entry page.' },
67
+ max_pages: { type: 'integer', minimum: 1, maximum: 50, description: 'Pages to crawl (default 6).' },
68
+ now: { type: 'string', description: 'ISO-8601 reference time for freshness checks.' },
69
+ },
70
+ required: ['url'],
71
+ },
72
+ },
73
+ {
74
+ name: 'geo_generate_faq',
75
+ description:
76
+ 'Build FAQPage JSON-LD from question-shaped headings that already have a real answer on the page. Returns no document when the site has none, instead of fabricating questions. Google restricted FAQ rich results to authoritative government and health sites in August 2023, so this markup does not earn rich results for most sites.',
77
+ inputSchema: {
78
+ type: 'object',
79
+ properties: {
80
+ url: { type: 'string', description: 'Absolute http(s) URL of the site entry page.' },
81
+ max_pages: { type: 'integer', minimum: 1, maximum: 50, description: 'Pages to crawl (default 6).' },
82
+ now: { type: 'string', description: 'ISO-8601 reference time for freshness checks.' },
83
+ },
84
+ required: ['url'],
85
+ },
86
+ },
87
+ {
88
+ name: 'geo_history',
89
+ description: 'List recent saved audits for this workspace, newest first, with totals and grades.',
90
+ inputSchema: {
91
+ type: 'object',
92
+ properties: {
93
+ limit: { type: 'integer', minimum: 1, maximum: 50, description: 'Entries to return (default 10).' },
94
+ },
95
+ },
96
+ },
97
+ ];
98
+
99
+ function errorMessage(error) {
100
+ return error && error.message ? error.message : String(error);
101
+ }
102
+
103
+ function assertString(value, name) {
104
+ if (typeof value !== 'string' || value.trim() === '') throw new Error(`${name} must be a non-empty string`);
105
+ return value;
106
+ }
107
+
108
+ /**
109
+ * Run one tool call.
110
+ * @param {string} name - Tool name from the client.
111
+ * @param {object} args - Parsed arguments.
112
+ * @param {{cwd: string, allowPrivate?: boolean, insecureTls?: boolean}} context - Workspace root for
113
+ * reports. `allowPrivate` exists for local fixtures only; the stdio server
114
+ * never sets it, so a public MCP client cannot reach loopback addresses.
115
+ * @returns {Promise<{content: Array<{type: string, text: string}>, isError?: boolean}>}
116
+ */
117
+ export async function callTool(name, args, context) {
118
+ const input = args !== null && typeof args === 'object' ? args : {};
119
+ const { cwd } = context;
120
+
121
+ if (name === 'geo_scan') {
122
+ const url = assertString(input.url, 'url');
123
+ if (input.max_pages !== undefined && (!Number.isInteger(input.max_pages) || input.max_pages < 1 || input.max_pages > 50)) {
124
+ throw new Error('max_pages must be an integer between 1 and 50');
125
+ }
126
+ if (input.now !== undefined && !Number.isFinite(Date.parse(input.now))) {
127
+ throw new Error('now must be an ISO-8601 timestamp');
128
+ }
129
+ const { scan, report } = await auditSite(url, {
130
+ maxPages: input.max_pages,
131
+ now: input.now ?? undefined,
132
+ allowPrivate: context.allowPrivate === true,
133
+ insecureTls: context.insecureTls === true,
134
+ });
135
+
136
+ // Save by default: an MCP client's next call is usually geo_fix_plan, which
137
+ // reads the persisted report. `save: false` keeps a pure snapshot.
138
+ let persisted = null;
139
+ if (input.save !== false) {
140
+ persisted = await persistAudit(cwd, { scan, report });
141
+ }
142
+
143
+ const text = summariseScanForModel(scan, report);
144
+ return {
145
+ content: [{
146
+ type: 'text',
147
+ text: persisted
148
+ ? `${text}\n\nSaved to .dsh-geo/latest.json (report: .dsh-geo/report.md)`
149
+ : `${text}\n\nNot saved (save: false).`,
150
+ }],
151
+ };
152
+ }
153
+
154
+ if (name === 'geo_fix_plan') {
155
+ const { payload, plan } = await planFromReport(cwd, {
156
+ reportPath: input.report_path ? assertString(input.report_path, 'report_path') : undefined,
157
+ });
158
+ const lines = [
159
+ `Fix plan for ${payload.url ?? payload.score.startUrl} — ${payload.score.total}/100 (${payload.score.grade})`,
160
+ `${plan.actions.length} action(s). Wrote .dsh-geo/fix-plan.md and .dsh-geo/fix-plan.json.`,
161
+ '',
162
+ ];
163
+ plan.actions.slice(0, 10).forEach((action, index) => {
164
+ lines.push(`${index + 1}. [${action.dimensionTitle} ${action.weight}] ${action.title}`);
165
+ lines.push(` evidence: ${action.evidence}`);
166
+ lines.push(` fix: ${action.fix}`);
167
+ });
168
+ if (plan.actions.length > 10) lines.push(`… ${plan.actions.length - 10} more in fix-plan.md`);
169
+ lines.push('');
170
+ lines.push('This tool did not change the site. Apply the fixes in your own workflow, then run geo_scan again.');
171
+ return { content: [{ type: 'text', text: lines.join('\n') }] };
172
+ }
173
+
174
+ if (name === 'geo_generate_llms' || name === 'geo_generate_faq') {
175
+ const url = assertString(input.url, 'url');
176
+ const { scan } = await auditSite(url, {
177
+ maxPages: input.max_pages,
178
+ now: input.now ?? undefined,
179
+ allowPrivate: context.allowPrivate === true,
180
+ insecureTls: context.insecureTls === true,
181
+ });
182
+ const { generateLlmsTxt, generateFaqJsonLd, FAQ_NOTE } = await import('./generate.js');
183
+ if (name === 'geo_generate_llms') {
184
+ const llms = generateLlmsTxt(scan);
185
+ return {
186
+ content: [{
187
+ type: 'text',
188
+ text: `${llms.content}\n---\n${llms.links} link(s) from ${llms.sourcePages} crawled page(s). Review before publishing; this tool does not change the site.`,
189
+ }],
190
+ };
191
+ }
192
+ const faq = generateFaqJsonLd(scan);
193
+ if (!faq.json) {
194
+ return { content: [{ type: 'text', text: faq.skipped }] };
195
+ }
196
+ return {
197
+ content: [{
198
+ type: 'text',
199
+ text: `${JSON.stringify(faq.json, null, 2)}\n\n${faq.items.length} item(s). ${FAQ_NOTE}`,
200
+ }],
201
+ };
202
+ }
203
+
204
+ if (name === 'geo_history') {
205
+ const limit = input.limit === undefined ? 10 : input.limit;
206
+ if (!Number.isInteger(limit) || limit < 1 || limit > 50) throw new Error('limit must be an integer between 1 and 50');
207
+ const { listAudits, resolveStoreDir } = await import('./store.js');
208
+ const entries = await listAudits(resolveStoreDir(cwd), limit);
209
+ if (entries.length === 0) {
210
+ return { content: [{ type: 'text', text: 'No saved audits in this workspace yet. Run geo_scan first.' }] };
211
+ }
212
+ const lines = [`Recent audits (${entries.length}):`, ''];
213
+ for (const entry of entries) {
214
+ lines.push(`${entry.savedAt ?? 'unknown time'} ${entry.total} ${entry.grade} ${entry.url ?? ''}`);
215
+ }
216
+ return { content: [{ type: 'text', text: lines.join('\n') }] };
217
+ }
218
+
219
+ throw new Error(`Unknown tool: ${name}`);
220
+ }
221
+
222
+ /**
223
+ * Handle one JSON-RPC message.
224
+ *
225
+ * @param {object} message - Parsed request or notification.
226
+ * @param {{cwd: string, initialized: {value: boolean}}} state - Server state.
227
+ * @returns {Promise<object|null>} Response, or null for a notification.
228
+ */
229
+ export async function handleMessage(message, state) {
230
+ const isNotification = message.id === undefined || message.id === null;
231
+
232
+ if (message.jsonrpc !== '2.0' || typeof message.method !== 'string') {
233
+ if (isNotification) return null;
234
+ return {
235
+ jsonrpc: '2.0',
236
+ id: message.id ?? null,
237
+ error: { code: INVALID_REQUEST, message: 'Expected a JSON-RPC 2.0 request' },
238
+ };
239
+ }
240
+
241
+ const reply = (result) => (isNotification ? null : { jsonrpc: '2.0', id: message.id, result });
242
+ const fail = (code, text) => (isNotification ? null : { jsonrpc: '2.0', id: message.id, error: { code, message: text } });
243
+
244
+ switch (message.method) {
245
+ case 'initialize': {
246
+ state.initialized.value = true;
247
+ return reply({
248
+ protocolVersion: PROTOCOL_VERSION,
249
+ capabilities: { tools: { listChanged: false } },
250
+ serverInfo: SERVER_INFO,
251
+ });
252
+ }
253
+
254
+ case 'notifications/initialized':
255
+ case 'notifications/cancelled':
256
+ return null;
257
+
258
+ case 'ping':
259
+ return reply({});
260
+
261
+ case 'tools/list':
262
+ return reply({ tools: MCP_TOOLS });
263
+
264
+ case 'tools/call': {
265
+ const params = message.params ?? {};
266
+ const name = params.name;
267
+ if (typeof name !== 'string') return fail(INVALID_PARAMS, 'tools/call requires a tool name');
268
+ try {
269
+ const result = await callTool(name, params.arguments ?? {}, {
270
+ cwd: state.cwd,
271
+ allowPrivate: state.allowPrivate === true,
272
+ insecureTls: state.insecureTls === true,
273
+ });
274
+ return reply(result);
275
+ } catch (error) {
276
+ // A tool failure is a result, not a protocol error: the model needs to
277
+ // read it and decide what to do next.
278
+ return reply({ content: [{ type: 'text', text: `Error: ${errorMessage(error)}` }], isError: true });
279
+ }
280
+ }
281
+
282
+ default:
283
+ return fail(METHOD_NOT_FOUND, `Unsupported method: ${message.method}`);
284
+ }
285
+ }
286
+
287
+ /**
288
+ * Serve MCP over a pair of streams.
289
+ *
290
+ * @param {object} options
291
+ * @param {NodeJS.ReadableStream} options.input - Usually process.stdin.
292
+ * @param {NodeJS.WritableStream} options.output - Usually process.stdout.
293
+ * @param {string} options.cwd - Workspace root for reports.
294
+ * @param {(text: string) => void} [options.log] - Diagnostics sink (stderr).
295
+ * @returns {Promise<void>} Resolves when the input stream ends.
296
+ */
297
+ export function serve({ input, output, cwd, log = () => {}, allowPrivate = false, insecureTls = false }) {
298
+ const state = { cwd, allowPrivate, insecureTls, initialized: { value: false } };
299
+ let buffer = '';
300
+
301
+ const write = (message) => {
302
+ output.write(`${JSON.stringify(message)}\n`);
303
+ };
304
+
305
+ const handleLine = async (line) => {
306
+ const trimmed = line.trim();
307
+ if (trimmed === '') return;
308
+ let message;
309
+ try {
310
+ message = JSON.parse(trimmed);
311
+ } catch (error) {
312
+ write({ jsonrpc: '2.0', id: null, error: { code: PARSE_ERROR, message: `Invalid JSON: ${errorMessage(error)}` } });
313
+ return;
314
+ }
315
+ if (Array.isArray(message)) {
316
+ write({ jsonrpc: '2.0', id: null, error: { code: INVALID_REQUEST, message: 'Batch requests are not supported' } });
317
+ return;
318
+ }
319
+ try {
320
+ const response = await handleMessage(message, state);
321
+ if (response) write(response);
322
+ } catch (error) {
323
+ log(`dsh-geo mcp: ${errorMessage(error)}`);
324
+ write({
325
+ jsonrpc: '2.0',
326
+ id: message && message.id !== undefined ? message.id : null,
327
+ error: { code: INTERNAL_ERROR, message: errorMessage(error) },
328
+ });
329
+ }
330
+ };
331
+
332
+ return new Promise((resolve) => {
333
+ let chain = Promise.resolve();
334
+ input.setEncoding?.('utf8');
335
+ input.on('data', (chunk) => {
336
+ buffer += chunk;
337
+ let index = buffer.indexOf('\n');
338
+ while (index !== -1) {
339
+ const line = buffer.slice(0, index);
340
+ buffer = buffer.slice(index + 1);
341
+ // Serialize handling so responses stay ordered.
342
+ chain = chain.then(() => handleLine(line));
343
+ index = buffer.indexOf('\n');
344
+ }
345
+ });
346
+ input.on('end', () => {
347
+ if (buffer.trim() !== '') chain = chain.then(() => handleLine(buffer));
348
+ chain.then(resolve, resolve);
349
+ });
350
+ input.on('error', () => chain.then(resolve, resolve));
351
+ });
352
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cobola/dsh-geo",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
4
  "description": "Read-only, reproducible GEO/SEO website audits for DeepSeek Harness: inspect crawlability and citation-ready structure, return evidence and prioritized fixes, and never edit the site or promise rankings.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -22,7 +22,8 @@
22
22
  "./icon": "./icon.svg"
23
23
  },
24
24
  "bin": {
25
- "dsh-geo": "bin/dsh-geo.js"
25
+ "dsh-geo": "bin/dsh-geo.js",
26
+ "dsh-geo-mcp": "bin/dsh-geo-mcp.js"
26
27
  },
27
28
  "files": [
28
29
  "index.js",