@first-ch/tools-mcp 0.24.1 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -70,6 +70,7 @@ This server is also registered in the [MCP Registry](https://registry.modelconte
70
70
  | `sql_format` | Formats a SQL query that has been squashed onto a single line — uppercase keywords, a line break per clause and real indentation — the same logic as the browser tool at tools.first-ch.com/sql-format/. `SELECT` / `FROM` / `WHERE` / `GROUP BY` / `HAVING` / `ORDER BY` / `LIMIT` / `INSERT INTO` / `VALUES` / `UPDATE` / `SET` / `DELETE FROM` / `WITH` / `UNION` start a line and their contents are indented one level; joins start a line with `ON` indented below them; `AND` / `OR` break per condition, except the `AND` of `BETWEEN a AND b`. A parenthesis becomes an indented subquery only when `SELECT`, `WITH` or `VALUES` follows it, so function calls (`SUM(…)`, `IN (1, 2, 3)`, `OVER (PARTITION BY … ORDER BY …)`) stay on one line, and `CASE` gets `WHEN` / `ELSE` / `END` stacked. Only keywords and type names are re-cased — table, column and alias spellings are left exactly as typed, because identifier folding differs per database. Strings, quoted identifiers (`"…"` / `` `…` `` / `[…]`), comments and placeholders (`?` / `:name` / `$1` / `@var`) pass through verbatim. `notes` reports UPDATE or DELETE without a WHERE, unbalanced parentheses and quotes, `SELECT *`, implicit comma joins and placeholder usage. `compact` collapses everything back onto one line. It is a lexical formatter rather than a parser for one database, so MySQL, PostgreSQL, SQL Server, SQLite and Oracle dialects survive as written (syntax errors are not detected) | `text` or `path`, `outputPath?`, `keywordCase?` (`upper` default / `lower` / `preserve`), `functionCase?`, `indent?` (`2` / `4` default / `8` / `tab`), `commaStyle?` (`trailing` default / `leading`), `logicStyle?` (`leading` default / `trailing`), `breakColumns?`, `breakLogic?`, `breakOn?`, `breakCase?`, `breakSubquery?`, `expandClauses?`, `compact?`, `eol?` |
71
71
  | `qr_generate` | Turns a URL or any text into a QR code and returns it as SVG (vector), PNG or terminal-friendly text art — the same logic as the browser tool at tools.first-ch.com/qr/. Encoding (numeric, alphanumeric or UTF-8 byte mode, picked automatically from the input), Reed–Solomon error correction, the layout of finder, timing and alignment patterns, version information and the choice between the eight mask patterns are all implemented here (JIS X 0510 / ISO 18004, versions 1–40); there is no external API or image service. `ecLevel` trades capacity for damage tolerance (L about 7%, M about 15%, Q about 25%, H about 30% — use Q or H for print), `size` is the edge length in pixels, and `margin` is the quiet zone in modules (4 is the recommended default; 0 can break scanning over a patterned background). Wi-Fi (`WIFI:T:WPA;S:…;P:…;;`), `mailto:`, `tel:`, `SMSTO:` and `geo:` strings just go in as `text`. `outputPath` writes the file instead of returning the body; `format="png"` without it returns a data URI. Capacity tops out at 7,089 digits, 4,296 alphanumeric characters or 2,953 bytes (all at level L) | `text`, `ecLevel?` (`L` / `M` default / `Q` / `H`), `size?` (64–4096, default 320), `margin?` (0–32, default 4), `format?` (`svg` default / `png` / `text`), `mode?` (`auto` default / `numeric` / `alnum` / `byte`), `mask?` (0–7), `minVersion?`, `outputPath?` |
72
72
  | `unixtime_convert` | Converts Unix seconds, milliseconds, microseconds and nanoseconds to and from ISO 8601 and ordinary date strings — the same logic as the browser tool at tools.first-ch.com/unixtime/. The unit of a plain number is detected from its digit count (up to 10 digits seconds, up to 13 milliseconds, up to 16 microseconds, longer nanoseconds); `unit` states it outright instead. Digits below the millisecond are dropped and reported in `notes`. On the date side it accepts `2026-08-24T09:30:00Z` (ISO 8601), `2026-08-24 18:30`, `2026/8/24 9:05`, the Japanese `2026年8月24日 18時30分`, `Sun, 24 Aug 2026 03:00:00 GMT` (HTTP-date) and `now`, stripping the quotes, brackets and trailing commas that come with a paste from CSV or JSON. `input` takes one value per line, up to 500 lines at a time, and every row comes back with Unix seconds, milliseconds, ISO 8601 in UTC, local time in `timeZone` (with weekday and UTC offset) and a relative reading ("30分後" / "in 30 minutes"); a line that cannot be read fails on its own without taking the others down. **A date with no offset is read as a wall-clock time in `timeZone`** and always says so in `notes`; an explicit `+09:00` or `Z` in the input wins over `timeZone`. A wall-clock time that daylight saving skips is moved forward to the moment after the change, also noted. An 8-digit number such as `20260824` is Unix seconds here, so it is flagged in case a date was meant. Negative values (before 1970) and fractional seconds work | `input`, `timeZone?` (IANA name, default `UTC`), `unit?` (`auto` default / `s` / `ms` / `us` / `ns`), `now?` (Unix milliseconds or a date string, default the current time), `lang?` (`ja` default / `en`) |
73
+ | `robotstxt_generate` | Assembles a robots.txt from crawl rules, sitemap declarations and a preset for AI crawlers — the same logic as the browser tool at tools.first-ch.com/robots-txt/. `ai.preset` decides how 24 known AI crawlers are treated in one move: `training` (the default: refuse the ones that collect training data — GPTBot, ClaudeBot, Google-Extended, Bytespider, CCBot and the rest — while allowing AI search and on-demand fetchers such as OAI-SearchBot, Claude-SearchBot, PerplexityBot and ChatGPT-User), `allow`, `block`, `none` (leave AI crawlers out) or `custom` with `ai.overrides` naming them one by one. **A crawler obeys exactly one matching group**, so writing a group for GPTBot stops the `User-agent: *` rules from ever reaching it; by default the shared disallow paths are copied into the AI groups to close that gap (`ai.inherit: false` turns it off). Paths get a leading slash added and full URLs reduced to their path, and `warnings` reports spaces inside a path, non-ASCII paths that need percent-encoding, wildcards that not every crawler supports, a `Crawl-delay` Googlebot will ignore, a missing sitemap, a User-agent listed twice and a site blocked in full. `listCrawlers: true` returns just the crawler list (name, vendor, purpose) without generating anything | `siteUrl?`, `disallow?`, `allow?`, `userAgents?` (default `*`), `crawlDelay?`, `blockCrawlers?`, `sitemaps?`, `ai?` (`preset?`, `overrides?`, `inherit?`), `groups?`, `comments?` (default true), `allowStyle?` (`disallow-empty` default / `allow-slash`), `listCrawlers?`, `lang?` (`ja` default / `en`), `outputPath?` |
73
74
 
74
75
  See [`server.mjs`](./server.mjs) for the exact Zod input schemas.
75
76
 
@@ -182,6 +183,7 @@ claude mcp add firstch-tools -- npx -y @first-ch/tools-mcp
182
183
  | `sql_format` | 1行に固まったSQLを、予約語の大文字化・句ごとの改行・字下げの付いたクエリへ整形する。tools.first-ch.com/sql-format/ と同一の仕様。`SELECT` / `FROM` / `WHERE` / `GROUP BY` / `HAVING` / `ORDER BY` / `LIMIT` / `INSERT INTO` / `VALUES` / `UPDATE` / `SET` / `DELETE FROM` / `WITH` / `UNION` などの句を行頭へ、その中身を1段下げて並べ直す。JOIN は行頭に置いて `ON` を1段下げ、`AND` / `OR` は条件ごとに改行する(`BETWEEN a AND b` の `AND` は条件の区切りではないので改行しない)。`(` の直後が `SELECT` / `WITH` / `VALUES` のときだけサブクエリとみなして改行+字下げし、関数呼び出し(`SUM(…)` / `IN (1, 2, 3)` / `OVER (PARTITION BY … ORDER BY …)`)は1行のまま保つ。`CASE` 式は `WHEN` / `ELSE` / `END` を縦に並べる。予約語と型名だけを大文字(または小文字)へ揃え、**テーブル名・列名・別名の綴りは変えない**(識別子の折りたたみ方がDBごとに違うため)。文字列・引用符付き識別子(`"…"` / `` `…` `` / `[…]`)・コメント・プレースホルダ(`?` / `:name` / `$1` / `@var`)はそのまま残す。WHEREの無いUPDATE/DELETE・閉じていない括弧や引用符・`SELECT *`・暗黙の結合・プレースホルダの有無は `notes` で返す。`compact` を立てると逆に1行へ畳む。特定DBのパーサーではなく字句ベースの整形器なので、MySQL・PostgreSQL・SQL Server・SQLite・Oracle の方言も壊さずに通す(構文エラーの検出はしない) | `text` か `path`、`outputPath?`、`keywordCase?`(既定 `upper` / `lower` / `preserve`)、`functionCase?`、`indent?`(`2` / 既定 `4` / `8` / `tab`)、`commaStyle?`(既定 `trailing` / `leading`)、`logicStyle?`(既定 `leading` / `trailing`)、`breakColumns?`、`breakLogic?`、`breakOn?`、`breakCase?`、`breakSubquery?`、`expandClauses?`、`compact?`、`eol?` |
183
184
  | `qr_generate` | URL・テキストからQRコードを作り、SVG(ベクター)・PNG・端末に貼れる文字の図で返す。tools.first-ch.com/qr/ と同一の仕様。符号化(数字 / 英数字 / UTF-8のバイトモードを入力に応じて自動選択)・リード・ソロモン符号による誤り訂正・位置検出/タイミング/位置合わせパターンと型番情報の配置・8種類のマスクからの自動選択まで自前で実装しており(JIS X 0510 / ISO 18004・型番1〜40)、外部のAPIも画像生成サーバーも使わない。`ecLevel` は容量と汚れへの強さの取引(L 約7% / M 約15% / Q 約25% / H 約30%。印刷物はQ以上を推奨)、`size` は出力の一辺(px)、`margin` は余白=クワイエットゾーンのモジュール数(規格の推奨は4。0にすると背景の柄によっては読めなくなる)。Wi-Fi(`WIFI:T:WPA;S:…;P:…;;`)・`mailto:`・`tel:`・`SMSTO:`・`geo:` はその文字列をそのまま `text` に渡す。`outputPath` を渡すとファイルへ書き出す(本文は返さない)。`format="png"` で省いた場合は data URI で返る。容量の上限は数字7089桁・英数字4296文字・バイト2953文字(いずれもレベルL) | `text`、`ecLevel?`(`L` / 既定 `M` / `Q` / `H`)、`size?`(64〜4096・既定 320)、`margin?`(0〜32・既定 4)、`format?`(既定 `svg` / `png` / `text`)、`mode?`(既定 `auto` / `numeric` / `alnum` / `byte`)、`mask?`(0〜7)、`minVersion?`、`outputPath?` |
184
185
  | `unixtime_convert` | UNIX秒・ミリ秒・マイクロ秒・ナノ秒と、ISO 8601や日時文字列を相互に変換する。tools.first-ch.com/unixtime/ と同一の仕様。数値の単位は桁数から自動判定し(10桁までを秒 / 13桁までをミリ秒 / 16桁までをマイクロ秒 / それ以上をナノ秒)、`unit` を渡せばその単位で読む。ミリ秒より下の桁は切り捨て、その旨を `notes` で返す。日時側は `2026-08-24T09:30:00Z`(ISO 8601)・`2026-08-24 18:30`・`2026/8/24 9:05`・`2026年8月24日 18時30分`・`Sun, 24 Aug 2026 03:00:00 GMT`(HTTP-date)・`now` を受け付け、CSVやJSONから貼ったときの引用符・角括弧・行末カンマは自動で外す。`input` は1行1件で最大500行までまとめて変換し、行ごとにUNIX秒・ミリ秒・ISO 8601(UTC)・`timeZone` の現地時刻(曜日・UTCオフセット付き)・相対表示(○分前 / ○日後)を返す。読めなかった行は他の行を巻き込まずその行だけ `error` になる。**オフセットを持たない日時は `timeZone` の壁時計として解釈**し、必ず `notes` で明示する(入力に `+09:00` や `Z` があればそちらが優先)。夏時間で存在しない時刻は切り替え後へ繰り上げ、これも `notes` に出す。8桁の数字(`20260824`)はUNIX秒として読むため、日付のつもりの入力には注意を返す。負の値(1970年より前)と小数点付きの秒にも対応 | `input`、`timeZone?`(IANA名・既定 `UTC`)、`unit?`(既定 `auto` / `s` / `ms` / `us` / `ns`)、`now?`(UNIXミリ秒か日時文字列・既定は実行時刻)、`lang?`(既定 `ja` / `en`) |
186
+ | `robotstxt_generate` | クロールの許可/禁止ルール・サイトマップ宣言・AIクローラーの許可プリセットから robots.txt を組み立てる。tools.first-ch.com/robots-txt/ と同一の仕様。`ai.preset` で24種のAIクローラーの扱いをまとめて決められる: `training`(既定=GPTBot・ClaudeBot・Google-Extended・Bytespider・CCBot など**学習用データを集めるクローラーだけを拒否**し、OAI-SearchBot・Claude-SearchBot・PerplexityBot・ChatGPT-User などAI検索と都度取得は許可)/ `allow` / `block` / `none`(AIクローラーを書かない)/ `custom`(`ai.overrides` で1件ずつ指定)。**クローラーは自分に一致するグループを1つだけ読む**ため、GPTBot 用のグループを作った時点で `User-agent: *` の禁止ルールはそのクローラーへ届かなくなる。既定では共通の禁止パスをAI側のグループへ書き写してこの取りこぼしを防ぐ(`ai.inherit: false` で止められる)。パスは先頭の `/` を補い、絶対URLからはパス部分だけを取り出す。`warnings` では空白を含むパス・パーセントエンコードしていない日本語のパス・対応していないクローラーのあるワイルドカード・Googlebotが読まない `Crawl-delay`・サイトマップの宣言漏れ・同じUser-agentの重複・サイト全体の拒否を指摘する。`listCrawlers: true` を渡すと生成せずAIクローラーの一覧(名前・提供元・目的)だけを返す | `siteUrl?`、`disallow?`、`allow?`、`userAgents?`(既定 `*`)、`crawlDelay?`、`blockCrawlers?`、`sitemaps?`、`ai?`(`preset?` / `overrides?` / `inherit?`)、`groups?`、`comments?`(既定 true)、`allowStyle?`(既定 `disallow-empty` / `allow-slash`)、`listCrawlers?`、`lang?`(既定 `ja` / `en`)、`outputPath?` |
185
187
 
186
188
  正確な入力スキーマ(Zod定義)は [`server.mjs`](./server.mjs) を参照してください。
187
189
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@first-ch/tools-mcp",
3
- "version": "0.24.1",
4
- "description": "First CH Tools の計算ロジック(WCAGコントラスト比・文字数/Xウェイト・WebP変換・JSON-LD生成・llms.txt生成・文字コード/改行コード変換・Marp Markdown→スライド レンダリング・テストデータ生成・テキスト/コード差分・Cron式の解説・Base64/Data URI変換・URLパラメータの分解/再構築・HTML特殊文字のエスケープ/エンティティのデコード・JSON⇄YAMLの相互変換・px⇄rem/emの単位換算とCSSの一括変換・カラーコードの相互変換とアルファ透過の合成・MD5/SHA-1/SHA-256/SHA-384/SHA-512のハッシュ生成と照合・JWTのデコードと有効期限/署名の検証・User-Agent文字列の解析とデバイス判定・UUID v4/ULIDの一括生成・アスペクト比の計算とレスポンシブサイズの算出・TSV/CSVからMarkdownテーブルへの整形と相互変換・SQLクエリの整形と予約語の大文字化・URL/テキストからのQRコード生成・UNIXタイムスタンプと日時表記の相互変換)をMCPツールとして提供するサーバー",
3
+ "version": "0.25.0",
4
+ "description": "First CH Tools の計算ロジック(WCAGコントラスト比・文字数/Xウェイト・WebP変換・JSON-LD生成・llms.txt生成・文字コード/改行コード変換・Marp Markdown→スライド レンダリング・テストデータ生成・テキスト/コード差分・Cron式の解説・Base64/Data URI変換・URLパラメータの分解/再構築・HTML特殊文字のエスケープ/エンティティのデコード・JSON⇄YAMLの相互変換・px⇄rem/emの単位換算とCSSの一括変換・カラーコードの相互変換とアルファ透過の合成・MD5/SHA-1/SHA-256/SHA-384/SHA-512のハッシュ生成と照合・JWTのデコードと有効期限/署名の検証・User-Agent文字列の解析とデバイス判定・UUID v4/ULIDの一括生成・アスペクト比の計算とレスポンシブサイズの算出・TSV/CSVからMarkdownテーブルへの整形と相互変換・SQLクエリの整形と予約語の大文字化・URL/テキストからのQRコード生成・UNIXタイムスタンプと日時表記の相互変換・robots.txtの生成(AIクローラーの許可プリセット付き))をMCPツールとして提供するサーバー",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "firstch-tools-mcp": "server.mjs"
@@ -134,7 +134,14 @@
134
134
  "epoch",
135
135
  "iso8601",
136
136
  "datetime",
137
- "timezone"
137
+ "timezone",
138
+ "robots-txt",
139
+ "robots.txt",
140
+ "seo",
141
+ "gptbot",
142
+ "claudebot",
143
+ "ai-crawler",
144
+ "web-crawler"
138
145
  ],
139
146
  "author": "First CH LLC (https://first-ch.com)",
140
147
  "homepage": "https://tools.first-ch.com",
@@ -175,6 +182,7 @@
175
182
  "sql-format.mjs",
176
183
  "qr.mjs",
177
184
  "unixtime.mjs",
185
+ "robots-txt.mjs",
178
186
  "vendor/",
179
187
  "README.md",
180
188
  "LICENSE"
package/robots-txt.mjs ADDED
@@ -0,0 +1,503 @@
1
+ /* robots.txt ジェネレーター(robotstxt_generate)
2
+ * 生成コア(AI_CRAWLERS / buildRobotsTxt とその補助関数)は
3
+ * FirstCHTools の site/robots-txt/app.js と同一
4
+ * (2箇所ルール: site側が正本・片方を直したらもう片方も同じ内容で反映する)。
5
+ * 下のコアは site 側からそのまま持ってきたもので、両ファイルから
6
+ * コアの開始/終了コメントに挟まれた範囲を sed で切り出し(site側は字下げ2文字を落とす)、
7
+ * diff が空になることで同期を機械的に確認できる。
8
+ *
9
+ * クロールの許可/禁止・サイトマップ宣言・AIクローラー(GPTBot / ClaudeBot 等)の
10
+ * 許可プリセットから robots.txt を組み立て、書き間違いの指摘も返す。
11
+ * 完全ローカル処理・ネットワーク送信なし。 */
12
+
13
+ /* ==================== ここから生成コア(site / MCP で同一) ==================== */
14
+
15
+ export const AI_PRESETS = ['allow', 'block', 'training', 'none', 'custom'];
16
+ export const AI_DECISIONS = ['allow', 'block', 'omit'];
17
+
18
+ // AIクローラーの一覧。purpose は収集の目的で、robots.txt の書き分けの単位になる:
19
+ // training = モデルの学習データを集める / search = AI検索の索引を作る
20
+ // user = 利用者がURLを貼った・質問したときだけ取りに来る
21
+ // 「学習は断りたいが、AI検索には出したい」が典型的な要望なので purpose で分けられるようにしてある。
22
+ export const AI_CRAWLERS = [
23
+ { ua: 'GPTBot', vendor: 'OpenAI', purpose: 'training',
24
+ ja: 'ChatGPTのモデル学習に使うデータを集める', en: 'Collects data used to train OpenAI models' },
25
+ { ua: 'OAI-SearchBot', vendor: 'OpenAI', purpose: 'search',
26
+ ja: 'ChatGPTの検索結果に出すための索引を作る(学習には使われない)', en: 'Indexes pages so they can appear in ChatGPT search (not used for training)' },
27
+ { ua: 'ChatGPT-User', vendor: 'OpenAI', purpose: 'user',
28
+ ja: '利用者が貼ったURLをその場で読みに来る', en: 'Fetches a URL a user pasted into ChatGPT' },
29
+ { ua: 'ClaudeBot', vendor: 'Anthropic', purpose: 'training',
30
+ ja: 'Claudeのモデル学習に使うデータを集める', en: 'Collects data used to train Claude' },
31
+ { ua: 'Claude-SearchBot', vendor: 'Anthropic', purpose: 'search',
32
+ ja: 'Claudeの検索結果に出すための索引を作る', en: 'Indexes pages for Claude search results' },
33
+ { ua: 'Claude-User', vendor: 'Anthropic', purpose: 'user',
34
+ ja: '利用者の指示でそのページを読みに来る', en: 'Fetches a page when a user asks for it' },
35
+ { ua: 'Google-Extended', vendor: 'Google', purpose: 'training',
36
+ ja: 'Geminiの学習・回答の根拠づけに使う(Google検索の順位には影響しない)', en: 'Gemini training and grounding (does not affect Google Search ranking)' },
37
+ { ua: 'Applebot-Extended', vendor: 'Apple', purpose: 'training',
38
+ ja: 'Apple Intelligenceの学習に使う(検索用のApplebot本体とは別)', en: 'Apple Intelligence training (separate from Applebot, which is for search)' },
39
+ { ua: 'PerplexityBot', vendor: 'Perplexity', purpose: 'search',
40
+ ja: 'Perplexityの検索索引を作る', en: 'Indexes pages for Perplexity search' },
41
+ { ua: 'Perplexity-User', vendor: 'Perplexity', purpose: 'user',
42
+ ja: '利用者の質問に答えるためにそのページを読みに来る', en: 'Fetches a page to answer a user question' },
43
+ { ua: 'Meta-ExternalAgent', vendor: 'Meta', purpose: 'training',
44
+ ja: 'Meta AIの学習に使うデータを集める', en: 'Collects data used to train Meta AI' },
45
+ { ua: 'meta-externalfetcher', vendor: 'Meta', purpose: 'user',
46
+ ja: '利用者の指示でそのページを読みに来る', en: 'Fetches a page when a user asks for it' },
47
+ { ua: 'Amazonbot', vendor: 'Amazon', purpose: 'search',
48
+ ja: 'Alexaなどの回答に使うために読みに来る', en: 'Fetches pages to answer questions in Alexa and other services' },
49
+ { ua: 'Bytespider', vendor: 'ByteDance', purpose: 'training',
50
+ ja: 'ByteDance(TikTok運営)のモデル学習に使うデータを集める', en: 'Collects training data for ByteDance (TikTok) models' },
51
+ { ua: 'CCBot', vendor: 'Common Crawl', purpose: 'training',
52
+ ja: '公開データセットを作る(多くのLLMの学習元になっている)', en: 'Builds a public dataset that many LLMs are trained on' },
53
+ { ua: 'cohere-ai', vendor: 'Cohere', purpose: 'training',
54
+ ja: 'Cohereのモデル学習に使うデータを集める', en: 'Collects data used to train Cohere models' },
55
+ { ua: 'MistralAI-User', vendor: 'Mistral AI', purpose: 'user',
56
+ ja: 'Le Chatの利用者の指示で読みに来る', en: 'Fetches a page when a Le Chat user asks for it' },
57
+ { ua: 'DuckAssistBot', vendor: 'DuckDuckGo', purpose: 'search',
58
+ ja: 'DuckAssistの回答を作るために読みに来る', en: 'Fetches pages to build DuckAssist answers' },
59
+ { ua: 'YouBot', vendor: 'You.com', purpose: 'search',
60
+ ja: 'You.comの検索索引を作る', en: 'Indexes pages for You.com search' },
61
+ { ua: 'Diffbot', vendor: 'Diffbot', purpose: 'training',
62
+ ja: 'ナレッジグラフと学習用データセットを作る', en: 'Builds a knowledge graph and training datasets' },
63
+ { ua: 'ImagesiftBot', vendor: 'ImageSift', purpose: 'training',
64
+ ja: '画像のデータセットを作る', en: 'Builds image datasets' },
65
+ { ua: 'Omgilibot', vendor: 'Webz.io', purpose: 'training',
66
+ ja: '学習用データセットとして販売するために集める', en: 'Collects data that is sold as training datasets' },
67
+ { ua: 'Timpibot', vendor: 'Timpi', purpose: 'training',
68
+ ja: '分散型検索・データセット向けに集める', en: 'Collects data for a decentralised search index and datasets' },
69
+ { ua: 'anthropic-ai', vendor: 'Anthropic', purpose: 'training',
70
+ ja: '旧称(現在はClaudeBot。古い設定を残しているサイト向け)', en: 'Legacy name (now ClaudeBot; kept for older configurations)' },
71
+ ];
72
+
73
+ export const PURPOSE_LABEL = {
74
+ training: { ja: '学習', en: 'Training' },
75
+ search: { ja: 'AI検索', en: 'AI search' },
76
+ user: { ja: '利用者の指示', en: 'User-triggered' },
77
+ };
78
+
79
+ const ROBOTS_MSG = {
80
+ header: {
81
+ ja: () => '# robots.txt — First CH Tools (https://tools.first-ch.com/robots-txt/) で生成',
82
+ en: () => '# robots.txt — generated with First CH Tools (https://tools.first-ch.com/robots-txt/)',
83
+ },
84
+ headerSite: {
85
+ ja: (a) => `# 対象サイト: ${a.url}`,
86
+ en: (a) => `# Site: ${a.url}`,
87
+ },
88
+ sitemapComment: {
89
+ ja: () => 'サイトマップの場所(クロールの起点になる)',
90
+ en: () => 'Sitemap location (where crawlers start from)',
91
+ },
92
+ aiBlockComment: {
93
+ ja: (a) => `AIクローラー: 拒否(${a.n}件)`,
94
+ en: (a) => `AI crawlers: blocked (${a.n})`,
95
+ },
96
+ aiAllowComment: {
97
+ ja: (a) => `AIクローラー: 許可(${a.n}件)`,
98
+ en: (a) => `AI crawlers: allowed (${a.n})`,
99
+ },
100
+ aiAllowBlockedComment: {
101
+ ja: (a) => `AIクローラー: 許可の指定(${a.n}件)だが共通ルールでサイト全体を拒否`,
102
+ en: (a) => `AI crawlers: marked as allowed (${a.n}) but the shared rule blocks the whole site`,
103
+ },
104
+ pathFromUrl: {
105
+ ja: (a) => `絶対URLからパスだけを取り出しました(${a.from} → ${a.to})。robots.txt に書けるのは「/」で始まるパスだけです。`,
106
+ en: (a) => `Took just the path out of a full URL (${a.from} → ${a.to}). robots.txt only accepts paths that start with "/".`,
107
+ },
108
+ pathFixed: {
109
+ ja: (a) => `パスの先頭に「/」を補いました(${a.from} → ${a.to})。パスはサイトのルートからの絶対パスで書きます。`,
110
+ en: (a) => `Added the leading slash (${a.from} → ${a.to}). Paths are written from the site root.`,
111
+ },
112
+ pathSpace: {
113
+ ja: (a) => `「${a.value}」に空白が含まれています。robots.txt は空白でパスが切れるため、%20 に置き換えてください。`,
114
+ en: (a) => `"${a.value}" contains a space. A space ends the path in robots.txt, so write it as %20.`,
115
+ },
116
+ pathNonAscii: {
117
+ ja: (a) => `「${a.value}」にASCII以外の文字が含まれています。日本語のパスはパーセントエンコード(%E3%81%82 の形)で書くのが確実です。`,
118
+ en: (a) => `"${a.value}" contains non-ASCII characters. Percent-encode them (the %E3%81%82 form) to be safe.`,
119
+ },
120
+ pathWildcard: {
121
+ ja: (a) => `「${a.value}」はワイルドカード(* と $)を使っています。Google・Bing・OpenAIなど主要なクローラーは解釈しますが、対応していないクローラーは文字どおりに読みます。`,
122
+ en: (a) => `"${a.value}" uses wildcards (* and $). Google, Bing and OpenAI understand them, but crawlers that do not will read them literally.`,
123
+ },
124
+ crawlDelayIgnored: {
125
+ ja: () => 'Crawl-delay はGooglebotが解釈しません(Googleのクロール頻度はSearch Consoleで調整します)。Bing・Yandexなどには効きます。',
126
+ en: () => 'Googlebot ignores Crawl-delay (adjust Google crawl rate in Search Console). Bing and Yandex do honour it.',
127
+ },
128
+ crawlDelayInvalid: {
129
+ ja: (a) => `Crawl-delay の値「${a.value}」は0以上の数値ではないため出力しませんでした。`,
130
+ en: (a) => `Crawl-delay "${a.value}" is not a number of zero or more, so it was left out.`,
131
+ },
132
+ sitemapNotAbsolute: {
133
+ ja: (a) => `Sitemap は絶対URLで書く必要があります(「${a.value}」は http:// または https:// で始まっていません)。`,
134
+ en: (a) => `Sitemap must be an absolute URL ("${a.value}" does not start with http:// or https://).`,
135
+ },
136
+ noSitemap: {
137
+ ja: () => 'サイトマップが宣言されていません。「Sitemap: https://example.com/sitemap.xml」を入れておくと、クローラーがページの一覧を見つけやすくなります。',
138
+ en: () => 'No sitemap is declared. Adding "Sitemap: https://example.com/sitemap.xml" helps crawlers find every page.',
139
+ },
140
+ blockAll: {
141
+ ja: () => 'すべてのクローラーにサイト全体を拒否しています(User-agent: * に Disallow: /)。このまま公開すると検索結果に出なくなります。',
142
+ en: () => 'Every crawler is blocked from the whole site (Disallow: / under User-agent: *). Published as-is, the site will drop out of search results.',
143
+ },
144
+ blockAllSitemap: {
145
+ ja: () => 'サイト全体を拒否しているため、宣言したサイトマップもクローラーには読まれません。',
146
+ en: () => 'Because the whole site is blocked, crawlers will not read the sitemap you declared either.',
147
+ },
148
+ notNoindex: {
149
+ ja: () => 'Disallow はクロールを止めるだけで、すでに検索結果に載っているページを消すものではありません(他サイトからリンクされていればURLだけ残ることがあります)。消したいページには noindex を使います。',
150
+ en: () => 'Disallow only stops crawling; it does not remove pages already in the index (a URL linked from elsewhere can still be listed). Use noindex to drop a page.',
151
+ },
152
+ duplicateAgent: {
153
+ ja: (a) => `User-agent「${a.name}」が複数のグループに出てきます。クローラーは自分に一致するグループを1つだけ使うため、意図しない方が採用されることがあります。`,
154
+ en: (a) => `User-agent "${a.name}" appears in more than one group. A crawler obeys only one matching group, so the wrong one may win.`,
155
+ },
156
+ aiOwnGroup: {
157
+ ja: () => 'AIクローラーに専用のグループを作ると、そのクローラーは User-agent: * のルールを読まなくなります(一致するグループを1つだけ使う仕様のため)。共通の禁止パスはAI側のグループにも書き写す必要があります。',
158
+ en: () => 'Once an AI crawler has its own group it stops reading the User-agent: * rules (a crawler obeys only one matching group). Shared disallow paths must be repeated in the AI group.',
159
+ },
160
+ aiInherited: {
161
+ ja: (a) => `共通の禁止パス(${a.n}件)を、許可するAIクローラーのグループにも書き写しました。`,
162
+ en: (a) => `Copied the shared disallow paths (${a.n}) into the group for the AI crawlers you allow.`,
163
+ },
164
+ aiAllowButBlocked: {
165
+ ja: () => 'サイト全体を拒否しているため、許可としたAIクローラーにも Disallow: / が引き継がれています(結果としてどのAIも読めません)。',
166
+ en: () => 'The whole site is blocked, so the AI crawlers you allowed inherit Disallow: / as well — none of them can read anything.',
167
+ },
168
+ unlistedAllowed: {
169
+ ja: () => 'robots.txt は「書いていないものは許可」の仕組みです。一覧に無いクローラーや新しく登場したクローラーは、拒否したことになりません。',
170
+ en: () => 'robots.txt allows anything it does not mention. Crawlers missing from this list — including new ones — are not blocked.',
171
+ },
172
+ tooLarge: {
173
+ ja: (a) => `${a.kb} KB あります。Googleが読むのは先頭500KiBまでで、それ以降は無視されます。`,
174
+ en: (a) => `The file is ${a.kb} KB. Google only reads the first 500 KiB and ignores the rest.`,
175
+ },
176
+ ok: {
177
+ ja: () => '気になる点はありません。サイトのルート(https://example.com/robots.txt)に置いてください。',
178
+ en: () => 'Nothing to flag. Upload it to the site root (https://example.com/robots.txt).',
179
+ },
180
+ };
181
+
182
+ // 改行(オプションでカンマ)区切りの入力を、空行・コメント行・重複を落とした配列にする
183
+ export function robotsList(value, opts) {
184
+ const options = opts || {};
185
+ const raw = Array.isArray(value)
186
+ ? value.map((v) => String(v == null ? '' : v))
187
+ : String(value == null ? '' : value).split(/\r?\n/);
188
+ const parts = options.comma ? raw.reduce((acc, line) => acc.concat(line.split(',')), []) : raw;
189
+ const out = [];
190
+ for (const part of parts) {
191
+ const s = part.trim();
192
+ if (!s || s.charAt(0) === '#') continue;
193
+ if (out.indexOf(s) === -1) out.push(s);
194
+ }
195
+ return out;
196
+ }
197
+
198
+ // 同じ指摘は1回だけ積む(同じパスを2度書いても2行にしない)
199
+ function robotsWarn(warnings, level, code, lang, args) {
200
+ const entry = ROBOTS_MSG[code];
201
+ const message = entry ? entry[lang](args || {}) : code;
202
+ for (const w of warnings) if (w.code === code && w.message === message) return;
203
+ warnings.push({ level, code, message });
204
+ }
205
+
206
+ function robotsPath(value, warnings, lang) {
207
+ let s = String(value == null ? '' : value).trim();
208
+ if (!s) return '';
209
+ if (/^https?:\/\//i.test(s)) {
210
+ const m = s.match(/^https?:\/\/[^/]*(\/.*)?$/i);
211
+ const path = (m && m[1]) || '/';
212
+ robotsWarn(warnings, 'info', 'pathFromUrl', lang, { from: s, to: path });
213
+ s = path;
214
+ } else if (s.charAt(0) !== '/' && s.charAt(0) !== '*') {
215
+ const fixed = '/' + s;
216
+ robotsWarn(warnings, 'info', 'pathFixed', lang, { from: s, to: fixed });
217
+ s = fixed;
218
+ }
219
+ if (/\s/.test(s)) robotsWarn(warnings, 'warn', 'pathSpace', lang, { value: s });
220
+ if (/[^\x20-\x7E]/.test(s)) robotsWarn(warnings, 'info', 'pathNonAscii', lang, { value: s });
221
+ if (s.indexOf('*') !== -1 || s.indexOf('$') !== -1) robotsWarn(warnings, 'info', 'pathWildcard', lang, { value: s });
222
+ return s;
223
+ }
224
+
225
+ // AIクローラー1件ごとの扱い(allow / block / omit)を決める。overrides が個別指定
226
+ function robotsAiDecisions(ai) {
227
+ const conf = ai || {};
228
+ const preset = AI_PRESETS.indexOf(conf.preset) === -1 ? 'training' : conf.preset;
229
+ const overrides = conf.overrides || {};
230
+ const decisions = {};
231
+ for (const bot of AI_CRAWLERS) {
232
+ let d;
233
+ if (preset === 'allow') d = 'allow';
234
+ else if (preset === 'block') d = 'block';
235
+ else if (preset === 'training') d = bot.purpose === 'training' ? 'block' : 'allow';
236
+ else d = 'omit'; // none / custom は既定で書かない
237
+ const o = overrides[bot.ua];
238
+ if (AI_DECISIONS.indexOf(o) !== -1) d = o;
239
+ decisions[bot.ua] = d;
240
+ }
241
+ return { preset, decisions };
242
+ }
243
+
244
+ function robotsRenderGroup(group, opts) {
245
+ const lines = [];
246
+ const comments = opts.comments;
247
+ if (comments && group.comment) lines.push('# ' + group.comment);
248
+ const agents = group.userAgents.map((a) => (typeof a === 'string' ? { name: a, note: '' } : a));
249
+ const heads = agents.map((a) => 'User-agent: ' + a.name);
250
+ // 注釈を付ける行だけを見て桁を揃える(ボット名はASCIIなので文字数=表示幅)
251
+ let width = 0;
252
+ if (comments) heads.forEach((h, i) => { if (agents[i].note) width = Math.max(width, h.length); });
253
+ heads.forEach((h, i) => {
254
+ const note = comments ? agents[i].note : '';
255
+ lines.push(note ? h + new Array(Math.max(1, width - h.length + 2) + 1).join(' ') + '# ' + note : h);
256
+ });
257
+ const disallow = group.disallow || [];
258
+ const allow = group.allow || [];
259
+ if (!disallow.length && !allow.length) {
260
+ // 空の Disallow は「すべて許可」を意味する(1994年の原案から現在のRFC 9309まで共通)
261
+ lines.push(opts.allowStyle === 'allow-slash' ? 'Allow: /' : 'Disallow:');
262
+ } else {
263
+ for (const p of disallow) lines.push('Disallow: ' + p);
264
+ for (const p of allow) lines.push('Allow: ' + p);
265
+ }
266
+ if (group.crawlDelay != null) lines.push('Crawl-delay: ' + group.crawlDelay);
267
+ return lines.join('\n');
268
+ }
269
+
270
+ /* robots.txt を組み立てる。
271
+ * config = {
272
+ * groups: [{ userAgents, disallow, allow, crawlDelay, comment }], // 省略時は User-agent: * ひとつ
273
+ * ai: { preset: 'allow'|'block'|'training'|'none'|'custom', overrides: {UA: 'allow'|'block'|'omit'}, inherit },
274
+ * sitemaps, siteUrl, comments, allowStyle: 'disallow-empty'|'allow-slash', lang: 'ja'|'en'
275
+ * }
276
+ * 返り値 = { text, warnings, stats, ai } */
277
+ export function buildRobotsTxt(config) {
278
+ const conf = config || {};
279
+ const lang = conf.lang === 'en' ? 'en' : 'ja';
280
+ const comments = conf.comments !== false;
281
+ const allowStyle = conf.allowStyle === 'allow-slash' ? 'allow-slash' : 'disallow-empty';
282
+ const warnings = [];
283
+ const siteUrl = String(conf.siteUrl == null ? '' : conf.siteUrl).trim();
284
+
285
+ const inputGroups = Array.isArray(conf.groups) && conf.groups.length ? conf.groups : [{ userAgents: ['*'] }];
286
+ const groups = [];
287
+ for (const g of inputGroups) {
288
+ const source = g || {};
289
+ const agents = robotsList(source.userAgents == null ? '*' : source.userAgents, { comma: true });
290
+ const disallow = robotsList(source.disallow).map((p) => robotsPath(p, warnings, lang)).filter(Boolean);
291
+ const allow = robotsList(source.allow).map((p) => robotsPath(p, warnings, lang)).filter(Boolean);
292
+ let crawlDelay = null;
293
+ const rawDelay = source.crawlDelay;
294
+ if (rawDelay != null && String(rawDelay).trim() !== '') {
295
+ const n = Number(rawDelay);
296
+ if (!isFinite(n) || n < 0) {
297
+ robotsWarn(warnings, 'warn', 'crawlDelayInvalid', lang, { value: String(rawDelay) });
298
+ } else {
299
+ crawlDelay = n;
300
+ robotsWarn(warnings, 'info', 'crawlDelayIgnored', lang, {});
301
+ }
302
+ }
303
+ groups.push({
304
+ comment: source.comment || '',
305
+ userAgents: agents.length ? agents : ['*'],
306
+ disallow,
307
+ allow,
308
+ crawlDelay,
309
+ });
310
+ }
311
+
312
+ // 「*」のグループ=共通ルール。AIクローラーへ書き写す元になる
313
+ let base = null;
314
+ for (const g of groups) if (g.userAgents.indexOf('*') !== -1) { base = g; break; }
315
+
316
+ const { preset, decisions } = robotsAiDecisions(conf.ai);
317
+ const inherit = !(conf.ai && conf.ai.inherit === false);
318
+ const blockedBots = [];
319
+ const allowedBots = [];
320
+ for (const bot of AI_CRAWLERS) {
321
+ const d = decisions[bot.ua];
322
+ const entry = { name: bot.ua, note: bot.vendor + ' / ' + PURPOSE_LABEL[bot.purpose][lang] };
323
+ if (d === 'block') blockedBots.push(entry);
324
+ else if (d === 'allow') allowedBots.push(entry);
325
+ }
326
+ const aiGroups = [];
327
+ if (blockedBots.length) {
328
+ aiGroups.push({
329
+ comment: ROBOTS_MSG.aiBlockComment[lang]({ n: blockedBots.length }),
330
+ userAgents: blockedBots,
331
+ disallow: ['/'],
332
+ allow: [],
333
+ crawlDelay: null,
334
+ });
335
+ }
336
+ if (allowedBots.length) {
337
+ const inheritedDisallow = inherit && base ? base.disallow.slice() : [];
338
+ const inheritedAllow = inherit && base ? base.allow.slice() : [];
339
+ // 共通ルールが全体拒否のときは「許可」と書くと出力と食い違うので見出しを変える
340
+ const shutOut = inheritedDisallow.indexOf('/') !== -1;
341
+ const commentKey = shutOut ? 'aiAllowBlockedComment' : 'aiAllowComment';
342
+ aiGroups.push({
343
+ comment: ROBOTS_MSG[commentKey][lang]({ n: allowedBots.length }),
344
+ userAgents: allowedBots,
345
+ disallow: inheritedDisallow,
346
+ allow: inheritedAllow,
347
+ crawlDelay: null,
348
+ });
349
+ if (inheritedDisallow.length) robotsWarn(warnings, 'info', 'aiInherited', lang, { n: inheritedDisallow.length });
350
+ if (shutOut) robotsWarn(warnings, 'warn', 'aiAllowButBlocked', lang, {});
351
+ }
352
+ if (aiGroups.length) robotsWarn(warnings, 'info', 'aiOwnGroup', lang, {});
353
+ if (blockedBots.length) robotsWarn(warnings, 'info', 'unlistedAllowed', lang, {});
354
+
355
+ const allGroups = groups.concat(aiGroups);
356
+
357
+ // 同じUser-agentが2つのグループに出ていないか(クローラーは1グループしか読まない)
358
+ const seen = {};
359
+ for (const g of allGroups) {
360
+ for (const a of g.userAgents) {
361
+ const name = typeof a === 'string' ? a : a.name;
362
+ const key = name.toLowerCase();
363
+ if (seen[key]) robotsWarn(warnings, 'warn', 'duplicateAgent', lang, { name });
364
+ seen[key] = true;
365
+ }
366
+ }
367
+
368
+ const sitemaps = robotsList(conf.sitemaps).map((s) => {
369
+ if (!/^https?:\/\//i.test(s)) robotsWarn(warnings, 'warn', 'sitemapNotAbsolute', lang, { value: s });
370
+ return s;
371
+ });
372
+
373
+ const blocksAll = !!base && base.disallow.indexOf('/') !== -1;
374
+ if (blocksAll) {
375
+ robotsWarn(warnings, 'warn', 'blockAll', lang, {});
376
+ if (sitemaps.length) robotsWarn(warnings, 'info', 'blockAllSitemap', lang, {});
377
+ }
378
+ let ruleCount = 0;
379
+ for (const g of allGroups) ruleCount += g.disallow.length + g.allow.length;
380
+ if (ruleCount) robotsWarn(warnings, 'info', 'notNoindex', lang, {});
381
+ if (!sitemaps.length) robotsWarn(warnings, 'info', 'noSitemap', lang, {});
382
+
383
+ const blocks = [];
384
+ if (comments) {
385
+ const head = [ROBOTS_MSG.header[lang]({})];
386
+ if (siteUrl) head.push(ROBOTS_MSG.headerSite[lang]({ url: siteUrl }));
387
+ blocks.push(head.join('\n'));
388
+ }
389
+ for (const g of allGroups) blocks.push(robotsRenderGroup(g, { comments, allowStyle }));
390
+ if (sitemaps.length) {
391
+ const sm = [];
392
+ if (comments) sm.push('# ' + ROBOTS_MSG.sitemapComment[lang]({}));
393
+ for (const s of sitemaps) sm.push('Sitemap: ' + s);
394
+ blocks.push(sm.join('\n'));
395
+ }
396
+ const text = blocks.join('\n\n') + '\n';
397
+ const bytes = new TextEncoder().encode(text).length;
398
+ if (bytes > 512000) robotsWarn(warnings, 'warn', 'tooLarge', lang, { kb: Math.round(bytes / 102.4) / 10 });
399
+
400
+ return {
401
+ text,
402
+ warnings,
403
+ stats: {
404
+ groups: allGroups.length,
405
+ rules: ruleCount,
406
+ sitemaps: sitemaps.length,
407
+ lines: text.replace(/\n$/, '').split('\n').length,
408
+ bytes,
409
+ aiAllowed: allowedBots.length,
410
+ aiBlocked: blockedBots.length,
411
+ },
412
+ ai: { preset, decisions, allowed: allowedBots.map((b) => b.name), blocked: blockedBots.map((b) => b.name) },
413
+ };
414
+ }
415
+
416
+ /* ==================== ここまで生成コア ==================== */
417
+
418
+ /* ==================== MCPツールの入口(site側には無い) ==================== */
419
+
420
+ import { writeFile } from 'node:fs/promises';
421
+ import path from 'node:path';
422
+
423
+ const AI_PURPOSES = ['training', 'search', 'user'];
424
+
425
+ function assertEnum(value, allowed, label) {
426
+ if (value != null && allowed.indexOf(value) === -1) {
427
+ throw new Error(`${label} は ${allowed.join(' / ')} のいずれかを指定してください(受け取った値: ${JSON.stringify(value)})`);
428
+ }
429
+ }
430
+
431
+ /** AIクローラーの一覧を返す(生成せずに相手を確かめたいとき用) */
432
+ export function listAiCrawlers(lang = 'ja') {
433
+ const l = lang === 'en' ? 'en' : 'ja';
434
+ return {
435
+ count: AI_CRAWLERS.length,
436
+ purposes: AI_PURPOSES.map((p) => ({
437
+ purpose: p,
438
+ label: PURPOSE_LABEL[p][l],
439
+ crawlers: AI_CRAWLERS.filter((b) => b.purpose === p).map((b) => b.ua),
440
+ })),
441
+ crawlers: AI_CRAWLERS.map((b) => ({
442
+ userAgent: b.ua,
443
+ vendor: b.vendor,
444
+ purpose: b.purpose,
445
+ description: b[l],
446
+ })),
447
+ };
448
+ }
449
+
450
+ /** MCPツール robotstxt_generate の本体 */
451
+ export async function robotsTxtGenerate(opts = {}) {
452
+ const lang = opts.lang === 'en' ? 'en' : 'ja';
453
+ if (opts.listCrawlers) return listAiCrawlers(lang);
454
+
455
+ assertEnum(opts.allowStyle, ['disallow-empty', 'allow-slash'], 'allowStyle');
456
+ const ai = opts.ai ? { ...opts.ai } : {};
457
+ assertEnum(ai.preset, AI_PRESETS, 'ai.preset');
458
+ if (ai.overrides) {
459
+ for (const [ua, decision] of Object.entries(ai.overrides)) {
460
+ if (!AI_CRAWLERS.some((b) => b.ua === ua)) {
461
+ throw new Error(`ai.overrides の "${ua}" は一覧にないクローラーです(listCrawlers=true で一覧を取得できます)`);
462
+ }
463
+ assertEnum(decision, AI_DECISIONS, `ai.overrides["${ua}"]`);
464
+ }
465
+ }
466
+
467
+ let groups;
468
+ if (Array.isArray(opts.groups) && opts.groups.length) {
469
+ groups = opts.groups;
470
+ } else {
471
+ groups = [{
472
+ userAgents: opts.userAgents == null ? '*' : opts.userAgents,
473
+ disallow: opts.disallow,
474
+ allow: opts.allow,
475
+ crawlDelay: opts.crawlDelay,
476
+ }];
477
+ }
478
+ const others = robotsList(opts.blockCrawlers, { comma: true });
479
+ if (others.length) {
480
+ groups = groups.concat([{
481
+ comment: lang === 'en' ? 'Other crawlers you asked to stay out' : '個別に拒否したクローラー',
482
+ userAgents: others,
483
+ disallow: ['/'],
484
+ }]);
485
+ }
486
+
487
+ const result = buildRobotsTxt({
488
+ groups,
489
+ ai,
490
+ sitemaps: opts.sitemaps,
491
+ siteUrl: opts.siteUrl,
492
+ comments: opts.comments,
493
+ allowStyle: opts.allowStyle,
494
+ lang,
495
+ });
496
+
497
+ if (opts.outputPath) {
498
+ if (!path.isAbsolute(opts.outputPath)) throw new Error('outputPath は絶対パスで指定してください');
499
+ await writeFile(opts.outputPath, result.text, 'utf8');
500
+ return { written: opts.outputPath, warnings: result.warnings, stats: result.stats, ai: result.ai };
501
+ }
502
+ return result;
503
+ }
package/server.mjs CHANGED
@@ -27,6 +27,7 @@ import { markdownTable } from './markdown-table.mjs';
27
27
  import { sqlFormatTool } from './sql-format.mjs';
28
28
  import { qrGenerateTool } from './qr.mjs';
29
29
  import { unixtimeConvert } from './unixtime.mjs';
30
+ import { robotsTxtGenerate } from './robots-txt.mjs';
30
31
 
31
32
  const { version } = createRequire(import.meta.url)('./package.json');
32
33
  const server = new McpServer({ name: 'firstch-tools', version });
@@ -1112,4 +1113,86 @@ server.registerTool(
1112
1113
  },
1113
1114
  );
1114
1115
 
1116
+ server.registerTool(
1117
+ 'robotstxt_generate',
1118
+ {
1119
+ title: 'robots.txt の生成(AIクローラー対応)',
1120
+ description:
1121
+ 'クロールの許可/禁止ルール・サイトマップ宣言・AIクローラーの許可プリセットから robots.txt を組み立てる' +
1122
+ '(tools.first-ch.com/robots-txt/ と同一ロジック)。サイト公開前の robots.txt の作成、' +
1123
+ '「AIの学習には使わせたくないが、AI検索の結果には出したい」といった書き分けに使う。' +
1124
+ 'ai.preset で24種のAIクローラー(GPTBot / OAI-SearchBot / ClaudeBot / Claude-SearchBot / Google-Extended / ' +
1125
+ 'PerplexityBot / Bytespider / CCBot など)の扱いをまとめて決められる: ' +
1126
+ "'training'(既定=学習目的だけ拒否しAI検索と都度取得は許可) / 'allow'(全部許可) / 'block'(全部拒否) / " +
1127
+ "'none'(AIクローラーを書かない) / 'custom'(ai.overrides で1件ずつ指定)。" +
1128
+ '**クローラーは自分に一致するグループを1つだけ読む**ため、AI用のグループを作ると User-agent: * の禁止ルールが' +
1129
+ 'そのクローラーへ届かなくなる。既定では共通の禁止パスをAI側のグループへ書き写して取りこぼしを防ぐ' +
1130
+ '(ai.inherit=false で止められる)。' +
1131
+ 'パスは先頭の / の補完と絶対URLからのパス抽出を自動で行い、空白を含むパス・パーセントエンコードしていない' +
1132
+ '日本語のパス・ワイルドカード非対応クローラー・Googlebotが読まない Crawl-delay・サイトマップの宣言漏れ・' +
1133
+ '同じUser-agentの重複・サイト全体の拒否などを warnings で返す。' +
1134
+ 'listCrawlers=true を渡すと生成せずAIクローラーの一覧(名前・提供元・目的)だけを返す。' +
1135
+ 'outputPath を渡すとそのパスへ書き出す。完全ローカル処理・ネットワーク送信なし。',
1136
+ inputSchema: {
1137
+ siteUrl: z.string().optional().describe('対象サイトのURL(省略可。先頭のコメントに入るだけで動作は変えない)'),
1138
+ disallow: z
1139
+ .union([z.string(), z.array(z.string())])
1140
+ .optional()
1141
+ .describe('拒否するパス(User-agent: * に対する Disallow。改行区切りの文字列か配列。例: /admin/)'),
1142
+ allow: z
1143
+ .union([z.string(), z.array(z.string())])
1144
+ .optional()
1145
+ .describe('拒否の例外として許可するパス(Allow。改行区切りの文字列か配列)'),
1146
+ userAgents: z
1147
+ .union([z.string(), z.array(z.string())])
1148
+ .optional()
1149
+ .describe("基本グループの対象(既定 '*'。カンマまたは改行区切り)"),
1150
+ crawlDelay: z.number().optional().describe('Crawl-delay(秒)。Googlebotは解釈しない(warningsで知らせる)'),
1151
+ blockCrawlers: z
1152
+ .union([z.string(), z.array(z.string())])
1153
+ .optional()
1154
+ .describe('AI以外で個別に拒否したいクローラー名(例: AhrefsBot, SemrushBot)。Disallow: / のグループになる'),
1155
+ sitemaps: z
1156
+ .union([z.string(), z.array(z.string())])
1157
+ .optional()
1158
+ .describe('Sitemap として宣言する絶対URL(改行区切りの文字列か配列)'),
1159
+ ai: z
1160
+ .object({
1161
+ preset: z.enum(['allow', 'block', 'training', 'none', 'custom']).optional()
1162
+ .describe("AIクローラーのプリセット(既定 'training'=学習目的だけ拒否)"),
1163
+ overrides: z.record(z.enum(['allow', 'block', 'omit'])).optional()
1164
+ .describe("1件ずつの指定(例: {\"GPTBot\": \"block\", \"PerplexityBot\": \"allow\"})"),
1165
+ inherit: z.boolean().optional()
1166
+ .describe('共通の禁止パスを許可したAIクローラーのグループへ書き写すか(既定 true)'),
1167
+ })
1168
+ .optional()
1169
+ .describe('AIクローラーの扱い'),
1170
+ groups: z
1171
+ .array(
1172
+ z.object({
1173
+ userAgents: z.union([z.string(), z.array(z.string())]).optional(),
1174
+ disallow: z.union([z.string(), z.array(z.string())]).optional(),
1175
+ allow: z.union([z.string(), z.array(z.string())]).optional(),
1176
+ crawlDelay: z.number().optional(),
1177
+ comment: z.string().optional(),
1178
+ }),
1179
+ )
1180
+ .optional()
1181
+ .describe('グループを自分で並べたいとき(指定すると disallow / allow / userAgents / crawlDelay より優先)'),
1182
+ comments: z.boolean().optional().describe('説明のコメント行を入れるか(既定 true)'),
1183
+ allowStyle: z
1184
+ .enum(['disallow-empty', 'allow-slash'])
1185
+ .optional()
1186
+ .describe("すべて許可するときの書き方(既定 'disallow-empty'=空の Disallow:)"),
1187
+ listCrawlers: z.boolean().optional().describe('生成せずAIクローラーの一覧だけを返す'),
1188
+ lang: z.enum(['ja', 'en']).optional().describe("コメントと指摘事項の言語(既定 'ja')"),
1189
+ outputPath: z.string().optional().describe('robots.txt を書き出す絶対パス(指定すると本文は返さない)'),
1190
+ },
1191
+ },
1192
+ async (opts) => {
1193
+ await logUsage('robotstxt_generate');
1194
+ return asText(await robotsTxtGenerate(opts));
1195
+ },
1196
+ );
1197
+
1115
1198
  await server.connect(new StdioServerTransport());