@first-ch/tools-mcp 0.34.0 → 0.36.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
@@ -50,7 +50,7 @@ This server is also registered in the [MCP Registry](https://registry.modelconte
50
50
  | `jsonld_generate` | Generates schema.org JSON-LD for `organization` / `faqpage` / `service` / `breadcrumb`. Empty fields are omitted automatically. Returns both a `json` object and a ready-to-embed `<script>` snippet | `type`, plus the matching `organization` / `faq` / `service` / `breadcrumb` object |
51
51
  | `llmstxt_generate` | Generates an `llms.txt` file (per the llmstxt.org proposed format) summarizing a site for AI crawlers/agents | `siteName`, `summary?`, `notes?`, `sections?` |
52
52
  | `encoding_convert` | Detects the character encoding (UTF-8 / Shift_JIS), BOM and line endings (CRLF / LF / CR) of a file or text and converts it to UTF-8. Useful for diagnosing garbled Japanese CSVs and for normalising line endings. Output is UTF-8 only — encoding *to* Shift_JIS is not supported (no standard API, and a mapping table would be required). | `base64` or `text`, `mode` (`analyze` \| `convert`), `encoding`, `newline`, `bom` |
53
- | `marp_render` | Renders [Marp](https://marp.app) Markdown to slides. Emits a self-contained HTML file (theme CSS inlined; opens in a browser and prints one-slide-per-page) and optionally PDF. Ships a bundled Japanese theme `firstch` (firstch-design tokens: paper/ink/vermilion, IBM Plex Sans JP) used as the default theme. Marp front-matter in the Markdown (`theme:` / `paginate:` / `size:` / `<!-- _class: lead -->`) is honored. | `markdown` or `inputPath`, `theme?`, `formats?` (`html` \| `pdf`), `outputPath?`, `title?` |
53
+ | `marp_render` | Renders [Marp](https://marp.app) Markdown to slides. Emits a self-contained HTML file (theme CSS inlined; opens in a browser and prints one-slide-per-page) and optionally PDF. Ships a bundled Japanese theme `firstch` (paper/ink/vermilion; uses IBM Plex Sans JP if installed) used as the default theme. Marp front-matter in the Markdown (`theme:` / `paginate:` / `size:` / `<!-- _class: lead -->`) is honored. | `markdown` or `inputPath`, `theme?`, `formats?` (`html` \| `pdf`), `outputPath?`, `title?` |
54
54
  | `testdata_generate` | Generates dummy data for form / CSV-import testing. `mode=records` returns names, kana readings, addresses, postal codes, emails and phone numbers as CSV/TSV/JSON/XLSX with a choice of encoding (UTF-8 / Shift_JIS), BOM and line endings. `format=xlsx` returns a real Excel workbook as base64 (or writes it to `outputPath`) — the ZIP/OOXML parts are assembled directly, with no spreadsheet dependency, and postal codes and phone numbers are written as text cells so leading zeros survive; `mode=text` returns strings of exactly n-1 / n / n+1 characters for `maxlength` boundary tests. All output is fictional (emails use the RFC 2606 `example.com` family). Passing a `seed` makes the output reproducible | `mode?`, `rows?`, `fields?`, `format?`, `locale?`, `encoding?`, `newline?`, `bom?`, `header?`, `seed?`, `preset?`, `length?`, `outputPath?` |
55
55
  | `diff_check` | Compares two texts (or two files) and returns the added/removed/changed line counts plus a unified diff (`.patch`) — the same logic as the browser tool at tools.first-ch.com/diff/. Lines are matched with patience diff (lines occurring exactly once in both sides become anchors), falling back to Myers only inside anchor-less ranges. With `format=blocks` / `both`, paired changed lines are also compared at token level (runs of letters/digits are one token, CJK characters one each) and returned as `changed_parts`, so you can see *which words* changed. CRLF/CR/LF all count as the same line break; trailing-whitespace-only differences are ignored by default | `a`/`b` (text) or `pathA`/`pathB` (absolute paths), `format?` (`unified` \| `blocks` \| `both`), `context?`, `ignoreWhitespace?`, `ignoreCase?`, `words?` |
56
56
  | `cron_explain` | Explains a cron expression in plain language and returns the upcoming run times — the same logic as the browser tool at tools.first-ch.com/cron/. Parsing follows Vixie cron (`crontab(5)`): ranges, steps, lists, `JAN-DEC` / `SUN-SAT` names and the `@daily`-style shorthands; six fields means the first one is seconds (node-cron / Spring style). `warnings` call out the traps — day-of-month and day-of-week are OR'd (not AND'd) when both are restricted, `*/n` that does not divide its range evenly is not a uniform interval, and impossible dates such as February 30th never fire. Run times are found on the wall clock of the target time zone and converted back to real instants, so they stay correct across daylight-saving transitions | `expression`, `timeZone?` (IANA, default `UTC`), `count?` (default 5, max 100), `from?` (ISO 8601) |
@@ -87,6 +87,12 @@ See [`server.mjs`](./server.mjs) for the exact Zod input schemas.
87
87
 
88
88
  **PDF output (`marp_render`) needs a local Chrome/Chromium.** marp-core renders the HTML with no browser dependency (so the package stays light for `npx`); PDF is produced by driving a locally-installed Chrome/Chromium in headless mode. It is auto-detected on common paths, or set `MARP_CHROME_PATH` to the executable. If none is found, `marp_render` returns the HTML only and reports `pdf_skipped` — you can still open that HTML and print → PDF yourself (one slide per page).
89
89
 
90
+ ## Network access, files and privacy
91
+
92
+ - **No network access by default.** The only exceptions are `npx` downloading the package from the npm registry, and `marp_render` with `allowRemote: true` (your local Chrome/Chromium then fetches the remote images/stylesheets your Markdown references). By default `marp_render` loads no web fonts, keeps emoji as text, strips remote `@import`s from the built-in themes and runs Chrome with network access blocked and its sandbox enabled (`MARP_CHROME_NO_SANDBOX=1` opts out where the sandbox cannot start, e.g. root in a container).
93
+ - **No overwriting.** Tools that write files (`outputPath`/`outputDir`, `webp_convert`, `marp_render`) refuse to replace an existing file unless you pass `overwrite: true`. They are annotated `readOnlyHint: false` / `destructiveHint: true`; every other tool is `readOnlyHint: true`. `marp_render` without any path writes to `<OS temp dir>/firstch-tools-mcp/`; the server never deletes result files.
94
+ - Privacy policy: [plugins/firstch-tools/PRIVACY.md](./plugins/firstch-tools/PRIVACY.md). Bugs and questions: [GitHub Issues](https://github.com/First-CH/firstch-tools-mcp/issues).
95
+
90
96
  ## Telemetry
91
97
 
92
98
  Nothing is logged by default. Usage is recorded **only** when you set the `FIRSTCH_TOOLS_USAGE_LOG` environment variable to a file path — each tool call then appends one JSON line (`{ ts, tool, source }`) to that local file. There is no network transmission of any kind; if the variable is unset, no file is written and no data leaves your machine.
@@ -174,7 +180,7 @@ claude mcp add firstch-tools -- npx -y @first-ch/tools-mcp
174
180
  | `jsonld_generate` | schema.org準拠のJSON-LDを生成する(`organization` / `faqpage` / `service` / `breadcrumb`)。空項目は自動で省略。`json`オブジェクトと埋め込み用`<script>`スニペットの両方を返す | `type` と対応する `organization` / `faq` / `service` / `breadcrumb` オブジェクト |
175
181
  | `llmstxt_generate` | AI検索・生成AI向けにサイト概要を伝える `llms.txt`(llmstxt.org提案フォーマット準拠)を生成する | `siteName`・`summary?`・`notes?`・`sections?` |
176
182
  | `encoding_convert` | ファイル/テキストの文字コード(UTF-8 / Shift_JIS)・BOM有無・改行コード(CRLF / LF / CR)を判定し、UTF-8へ変換する。日本語CSVの文字化け調査、改行コードの統一に。**出力はUTF-8のみ**(Shift_JISへのエンコードは標準APIに無く変換表が必要なため非対応) | `base64` または `text`、`mode`(`analyze` \| `convert`)、`encoding`、`newline`、`bom` |
177
- | `marp_render` | [Marp](https://marp.app) Markdown をスライドへレンダリングする。テーマCSSをインラインした自己完結HTML(ブラウザで開けて、印刷すると1スライド=1ページ)と、任意でPDFを書き出す。和文テーマ `firstch`(firstch-design トークン: 紙/墨/朱・IBM Plex Sans JP)を同梱し既定テーマにする。Markdown内の Marp フロントマター(`theme:` / `paginate:` / `size:` / `<!-- _class: lead -->`)はそのまま効く | `markdown` または `inputPath`、`theme?`、`formats?`(`html` \| `pdf`)、`outputPath?`、`title?` |
183
+ | `marp_render` | [Marp](https://marp.app) Markdown をスライドへレンダリングする。テーマCSSをインラインした自己完結HTML(ブラウザで開けて、印刷すると1スライド=1ページ)と、任意でPDFを書き出す。和文テーマ `firstch`(紙/墨/朱・IBM Plex Sans JP が入っていれば使う)を同梱し既定テーマにする。Markdown内の Marp フロントマター(`theme:` / `paginate:` / `size:` / `<!-- _class: lead -->`)はそのまま効く | `markdown` または `inputPath`、`theme?`、`formats?`(`html` \| `pdf`)、`outputPath?`、`title?` |
178
184
  | `testdata_generate` | フォーム入力・CSV取り込みテスト用のダミーデータを生成する。`mode=records` は氏名・フリガナ・住所・郵便番号・メール・電話番号などをCSV/TSV/JSON/XLSXで返し、文字コード(UTF-8 / Shift_JIS)・BOM・改行コードを指定できる。`format=xlsx` は Excel ファイル本体を base64(または `outputPath` へ書き出し)で返す。ZIP+OOXMLを依存ライブラリなしで直接組み立てており、郵便番号・電話番号は文字列セルにするため先頭の0が消えない。`mode=text` は `maxlength` の境界値テスト用に n-1 / n / n+1 文字ちょうどの文字列を返す。生成データはすべて架空(メールは RFC 2606 の `example.com` 系)。`seed` を渡すと同じデータを再現できる | `mode?`・`rows?`・`fields?`・`format?`・`locale?`・`encoding?`・`newline?`・`bom?`・`header?`・`seed?`・`preset?`・`length?`・`outputPath?` |
179
185
  | `diff_check` | 2つのテキスト(またはファイル)を比較し、追加/削除/変更の行数と unified diff(`.patch`)を返す。tools.first-ch.com/diff/ と同一ロジック。行の対応づけは patience diff(両方に1回だけ現れる行をアンカーに分割)+アンカーの取れない範囲だけ Myers。`format=blocks` / `both` では、変更行のペアを語単位(英数字はひとかたまり・和文は1文字ずつ)でも比較し `changed_parts` として返すため「どの語が変わったか」まで取れる。CRLF/CR/LF は同じ行区切りとして扱い、行末の空白だけの差は既定で無視する | `a`/`b`(テキスト)または `pathA`/`pathB`(絶対パス)、`format?`(`unified` \| `blocks` \| `both`)、`context?`、`ignoreWhitespace?`、`ignoreCase?`、`words?` |
180
186
  | `cron_explain` | Cron式を人間向けの文へ読み下し、次回からの発火日時を返す。tools.first-ch.com/cron/ と同一ロジック。解釈は Vixie cron(`crontab(5)`)準拠で、範囲・ステップ・列挙・`JAN-DEC` / `SUN-SAT` の名前・`@daily` 等の省略記法に対応し、6フィールドのときは先頭を秒として扱う(node-cron / Spring 形式)。誤りやすい点は `warnings` で知らせる(「日」と「曜日」の両方指定は AND ではなく OR、範囲を割り切らない `*/n` は等間隔にならない、2月30日のような存在しない日付は発火しない)。発火日時はタイムゾーンの壁時計上で求めてから実時刻へ戻すため、夏時間のある地域でもずれない | `expression`、`timeZone?`(IANA名・既定 `UTC`)、`count?`(既定5・最大100)、`from?`(ISO 8601) |
@@ -211,6 +217,12 @@ claude mcp add firstch-tools -- npx -y @first-ch/tools-mcp
211
217
 
212
218
  **`marp_render` のPDF出力にはローカルの Chrome/Chromium が必要です。** marp-core によるHTML生成はブラウザ非依存(`npx` 導入を軽く保つため)で、PDFはローカルインストール済みの Chrome/Chromium を headless で駆動して生成します。定番パスから自動検出し、`MARP_CHROME_PATH` で実行ファイルを明示することもできます。見つからない場合は HTML のみを返し `pdf_skipped` を報告します(そのHTMLを開いて印刷→PDF保存でも1スライド=1ページで作成できます)。
213
219
 
220
+ ### 通信・ファイル・プライバシー
221
+
222
+ - **既定では外部へ通信しません。** 例外は起動時に `npx` が npm レジストリからパッケージを取得することと、`marp_render` に `allowRemote: true` を渡したとき(Markdown が参照する外部の画像・CSS をローカルの Chrome が読み込む)だけです。既定の `marp_render` は Webフォントを読まず、絵文字は文字のまま、組み込みテーマの外部 `@import` を取り除き、Chrome も外部通信を止めサンドボックス有効のまま起動します(サンドボックスが使えない環境だけ `MARP_CHROME_NO_SANDBOX=1` で外せます)。
223
+ - **上書きしません。** ファイルを書くツール(`outputPath`/`outputDir` を持つもの・`webp_convert`・`marp_render`)は、同名のファイルがあれば `overwrite: true` を渡さない限りエラーにします。これらは `readOnlyHint: false`・`destructiveHint: true`、それ以外は `readOnlyHint: true` を付けています。パス指定の無い `marp_render` は `<OSの一時ディレクトリ>/firstch-tools-mcp/` に書き、書いたファイルはサーバーが消しません。
224
+ - プライバシーポリシー: [plugins/firstch-tools/PRIVACY.md](./plugins/firstch-tools/PRIVACY.md)。不具合・質問: [GitHub Issues](https://github.com/First-CH/firstch-tools-mcp/issues)。
225
+
214
226
  ### 計測(Telemetry)について
215
227
 
216
228
  既定では何も記録しません。環境変数 `FIRSTCH_TOOLS_USAGE_LOG` にファイルパスを設定したときのみ、各ツール呼び出しごとに1行のJSON(`{ ts, tool, source }`)をそのローカルファイルへ追記します。ネットワーク送信は一切ありません(未設定であればファイルへの書き込み自体が発生せず、データが端末外に出ることはありません)。
package/base64.mjs CHANGED
@@ -4,7 +4,8 @@
4
4
  // 2箇所ルール: 片方を直したらもう片方も同じ内容で直す(site側が正本)。
5
5
  // btoa / atob / TextEncoder / TextDecoder は Node 18+ にグローバルで存在するため、
6
6
  // ブラウザ版のコードをそのまま持ってこられる(環境差で結果がずれない)。
7
- import { readFile, writeFile } from 'node:fs/promises';
7
+ import { readFile } from 'node:fs/promises';
8
+ import { writeOutput } from './fs-safe.mjs';
8
9
  import { basename } from 'node:path';
9
10
 
10
11
  /* ==================== ここから変換コア(site/base64/app.js と同一) ==================== */
@@ -285,7 +286,7 @@ export async function base64Convert(opts = {}) {
285
286
  suggested_extension: extForMime(mimeType),
286
287
  };
287
288
  if (opts.outputPath) {
288
- await writeFile(opts.outputPath, bytes);
289
+ await writeOutput(opts.outputPath, bytes, { overwrite: opts.overwrite });
289
290
  result.output = opts.outputPath;
290
291
  // ファイルに書けたなら base64 は重複した重い情報でしかない
291
292
  delete result.base64;
package/case-convert.mjs CHANGED
@@ -3,7 +3,8 @@
3
3
  // 「変換コア」ブロックは site 側の site/case/app.js と同一の実装。
4
4
  // 2箇所ルール: 片方を直したらもう片方も同じ内容で直す(site側が正本)。
5
5
  // 使っているのは String/RegExp だけなので、ブラウザ版のコードをそのまま持ってこられる。
6
- import { readFile, writeFile } from 'node:fs/promises';
6
+ import { readFile } from 'node:fs/promises';
7
+ import { writeOutput } from './fs-safe.mjs';
7
8
  import { basename } from 'node:path';
8
9
 
9
10
  /* ==================== ここから変換コア(site / MCP で同一) ==================== */
@@ -381,7 +382,7 @@ export async function caseConvertTool(opts = {}) {
381
382
  })),
382
383
  };
383
384
  if (opts.outputPath) {
384
- await writeFile(opts.outputPath, r.text, 'utf8');
385
+ await writeOutput(opts.outputPath, r.text, { overwrite: opts.overwrite });
385
386
  result.output = opts.outputPath;
386
387
  // ファイルに書けたなら本文は重複した重い情報でしかない
387
388
  delete result.text;
package/csv-json.mjs CHANGED
@@ -8,7 +8,8 @@
8
8
  *
9
9
  * 使っているのは String/RegExp/JSON だけなので、ブラウザ版のコードをそのまま持ってこられる。
10
10
  * 完全ローカル処理・ネットワーク送信なし。 */
11
- import { readFile, writeFile } from 'node:fs/promises';
11
+ import { readFile } from 'node:fs/promises';
12
+ import { writeOutput } from './fs-safe.mjs';
12
13
  import { basename } from 'node:path';
13
14
 
14
15
  /* ==================== ここから変換コア(site / MCP で同一) ==================== */
@@ -846,7 +847,7 @@ export async function csvConvertTool(opts = {}) {
846
847
  result.output_bytes = r.output_bytes;
847
848
 
848
849
  if (o.outputPath) {
849
- await writeFile(o.outputPath, r.output, 'utf8');
850
+ await writeOutput(o.outputPath, r.output, { overwrite: o.overwrite });
850
851
  result.output_path = o.outputPath;
851
852
  // ファイルへ書けたなら本文は重複した重い情報でしかない
852
853
  } else {
package/fs-safe.mjs ADDED
@@ -0,0 +1,35 @@
1
+ // 出力ファイルの書き込み(MCPツール共通)
2
+ //
3
+ // 既定では既存ファイルを上書きしない('wx' フラグ=存在したら失敗)。
4
+ // AIが確認なしに利用者のファイルを消すのを防ぐため。上書きしたいときは
5
+ // 呼び出し側が overwrite: true を明示する(各ツールの inputSchema に overwrite がある)。
6
+
7
+ import { writeFile, mkdir } from 'node:fs/promises';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+
11
+ export class OutputExistsError extends Error {
12
+ constructor(file) {
13
+ super(`出力先に同名のファイルが既にあります: ${file}(上書きする場合は overwrite: true を渡してください)`);
14
+ this.code = 'EEXIST';
15
+ this.file = file;
16
+ }
17
+ }
18
+
19
+ export async function writeOutput(file, data, { overwrite = false } = {}) {
20
+ try {
21
+ await writeFile(file, data, { flag: overwrite ? 'w' : 'wx' });
22
+ } catch (e) {
23
+ if (e && e.code === 'EEXIST') throw new OutputExistsError(file);
24
+ throw e;
25
+ }
26
+ }
27
+
28
+ // 出力先を指定しなかったときの置き場(OSの一時ディレクトリの下の専用フォルダ)。
29
+ // ここへ書いたファイルは利用者が開くための成果物なので、サーバーは消さない。
30
+ // 置き場所を1か所に寄せて、まとめて消せるようにしている。
31
+ export async function defaultOutputDir() {
32
+ const dir = path.join(os.tmpdir(), 'firstch-tools-mcp');
33
+ await mkdir(dir, { recursive: true });
34
+ return dir;
35
+ }
package/html-escape.mjs CHANGED
@@ -3,7 +3,8 @@
3
3
  // 「変換コア」ブロックは site 側の site/html-escape/app.js と同一の実装。
4
4
  // 2箇所ルール: 片方を直したらもう片方も同じ内容で直す(site側が正本)。
5
5
  // 使っているのは String/RegExp だけなので、ブラウザ版のコードをそのまま持ってこられる。
6
- import { readFile, writeFile } from 'node:fs/promises';
6
+ import { readFile } from 'node:fs/promises';
7
+ import { writeOutput } from './fs-safe.mjs';
7
8
  import { basename } from 'node:path';
8
9
 
9
10
  /* ==================== ここから変換コア(site/html-escape/app.js と同一) ==================== */
@@ -299,7 +300,7 @@ export async function htmlEscape(opts = {}) {
299
300
  result.invalid_references = r.invalid;
300
301
  }
301
302
  if (opts.outputPath) {
302
- await writeFile(opts.outputPath, r.text, 'utf8');
303
+ await writeOutput(opts.outputPath, r.text, { overwrite: opts.overwrite });
303
304
  result.output = opts.outputPath;
304
305
  // ファイルに書けたなら本文は重複した重い情報でしかない
305
306
  delete result.text;
package/html-md.mjs CHANGED
@@ -6,7 +6,8 @@
6
6
  // 挟んだ範囲を sed で切り出して diff すれば同期漏れを機械確認できる(csv-json.mjs と同じ手順。
7
7
  // 手順そのものは FirstCHTools の CLAUDE.md を参照)。追記は必ずコアの終わりより下へ。
8
8
  // DOM(DOMParser / innerHTML)に依存しないので、Node でもブラウザでも同じ結果になる。
9
- import { readFile, writeFile } from 'node:fs/promises';
9
+ import { readFile } from 'node:fs/promises';
10
+ import { writeOutput } from './fs-safe.mjs';
10
11
  import { basename } from 'node:path';
11
12
 
12
13
  /* ==================== ここから変換コア(site / MCP で同一) ==================== */
@@ -1217,7 +1218,7 @@ export async function htmlToMarkdownTool(opts = {}) {
1217
1218
  result.references = r.refs.map((ref) => ({ id: ref.id, url: ref.url, title: ref.title || null }));
1218
1219
  }
1219
1220
  if (o.outputPath) {
1220
- await writeFile(o.outputPath, r.markdown, 'utf8');
1221
+ await writeOutput(o.outputPath, r.markdown, { overwrite: o.overwrite });
1221
1222
  result.output = o.outputPath;
1222
1223
  // ファイルに書けたなら本文は重複した重い情報でしかない
1223
1224
  delete result.markdown;
package/json-yaml.mjs CHANGED
@@ -4,7 +4,8 @@
4
4
  // 2箇所ルール: 片方を直したらもう片方も同じ内容で直す(site側が正本)。
5
5
  // 使っているのは String / RegExp / Object だけなので、ブラウザ版のコードをそのまま持ってこられる
6
6
  // (YAMLの解析・生成も自前実装で、js-yaml 等の外部ライブラリには依存しない)。
7
- import { readFile, writeFile } from 'node:fs/promises';
7
+ import { readFile } from 'node:fs/promises';
8
+ import { writeOutput } from './fs-safe.mjs';
8
9
  import { basename } from 'node:path';
9
10
 
10
11
  /* ==================== ここから変換コア(site / MCP で同一) ==================== */
@@ -1630,7 +1631,7 @@ async function convert(direction, opts) {
1630
1631
  };
1631
1632
 
1632
1633
  if (o.outputPath) {
1633
- await writeFile(o.outputPath, r.output, 'utf8');
1634
+ await writeOutput(o.outputPath, r.output, { overwrite: o.overwrite });
1634
1635
  result.output = o.outputPath;
1635
1636
  // ファイルに書けたなら本文は重複した重い情報でしかない
1636
1637
  delete result.text;
package/lib.mjs CHANGED
@@ -155,7 +155,9 @@ export function buildJsonLd(type, fields = {}) {
155
155
  const builder = jsonLdBuilders[type];
156
156
  if (!builder) throw new Error(`未対応タイプ: ${type}(organization / faqpage / service / breadcrumb のいずれか)`);
157
157
  const json = builder(fields);
158
- const snippet = `<script type="application/ld+json">\n${JSON.stringify(json, null, 2)}\n</script>`;
158
+ // 値に </script> や <!-- があってもスクリプト要素から抜けないよう、< を \u003c にする(JSONとしては同じ値)
159
+ const body = JSON.stringify(json, null, 2).replace(/</g, '\\u003c');
160
+ const snippet = `<script type="application/ld+json">\n${body}\n</script>`;
159
161
  return { json, snippet };
160
162
  }
161
163
 
@@ -3,7 +3,8 @@
3
3
  // 「変換コア」ブロックは site 側の site/markdown-table/app.js と同一の実装。
4
4
  // 2箇所ルール: 片方を直したらもう片方も同じ内容で直す(site側が正本)。
5
5
  // 使っているのは String/RegExp/Array だけなので、ブラウザ版のコードをそのまま持ってこられる。
6
- import { readFile, writeFile } from 'node:fs/promises';
6
+ import { readFile } from 'node:fs/promises';
7
+ import { writeOutput } from './fs-safe.mjs';
7
8
  import { basename } from 'node:path';
8
9
 
9
10
  /* ==================== ここから変換コア(site / MCP で同一) ==================== */
@@ -632,7 +633,7 @@ export async function markdownTable(opts = {}) {
632
633
  notes,
633
634
  };
634
635
  if (opts.outputPath) {
635
- await writeFile(opts.outputPath, text, 'utf8');
636
+ await writeOutput(opts.outputPath, text, { overwrite: opts.overwrite });
636
637
  result.output = opts.outputPath;
637
638
  // ファイルに書けたなら本文は重複した重い情報でしかない
638
639
  delete result.text;
package/marp.mjs CHANGED
@@ -8,10 +8,18 @@
8
8
  // HTMLから印刷する(puppeteer/Chromium を同梱しない=`npx -y` 導入を軽く保つ)。
9
9
  // Chrome が見つからない場合は HTML のみ返し、PDFは skip して理由を添える。
10
10
  //
11
- // 和文テーマ firstch(firstch-design 準拠)を marp-theme.css として同梱し、
11
+ // 和文テーマ firstch を marp-theme.css として同梱し、
12
12
  // Markdown が theme 指示を持たないときの既定テーマにする。
13
+ //
14
+ // 通信について(既定=外へ取りに行かない):
15
+ // - Webフォントは読み込まない(OSにあるフォントで描く。IBM Plex Sans JP が入っていれば使う)
16
+ // - 絵文字は画像(CDNの twemoji)に置き換えず、文字のまま出す
17
+ // - 組み込みテーマ(gaia/uncover)の CSS にある外部フォントの @import は取り除く
18
+ // - PDF を作る Chrome は外部への通信を止めて起動する
19
+ // allowRemote: true を渡したときだけ、Markdown が参照する外部の画像・CSS を読み込む。
13
20
 
14
21
  import { readFile, writeFile, rm } from 'node:fs/promises';
22
+ import { writeOutput, defaultOutputDir, OutputExistsError } from './fs-safe.mjs';
15
23
  import { existsSync } from 'node:fs';
16
24
  import { execFile } from 'node:child_process';
17
25
  import { promisify } from 'node:util';
@@ -71,16 +79,28 @@ function slideSize(html, css) {
71
79
  return { w: 1280, h: 720 };
72
80
  }
73
81
 
82
+ // <title> へ入れる文字列のエスケープ(</title><script> の注入を防ぐ)
83
+ export function escapeHtml(s) {
84
+ return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
85
+ }
86
+
87
+ // CSS の外部 @import(例: gaia テーマの fonts.bunny.net)を取り除く。取り除いた URL を返す。
88
+ export function stripRemoteImports(css) {
89
+ const removed = [];
90
+ const out = css.replace(/@import\s+(?:url\(\s*)?(["']?)((?:https?:)?\/\/[^"')\s;]+)\1\s*\)?[^;]*;/gi, (_m, _q, url) => {
91
+ removed.push(url);
92
+ return '';
93
+ });
94
+ return { css: out, removed };
95
+ }
96
+
74
97
  function buildHtmlDoc({ html, css, size, title }) {
75
98
  return `<!DOCTYPE html>
76
99
  <html lang="ja">
77
100
  <head>
78
101
  <meta charset="utf-8">
79
102
  <meta name="viewport" content="width=device-width, initial-scale=1">
80
- <title>${title}</title>
81
- <link rel="preconnect" href="https://fonts.googleapis.com">
82
- <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
83
- <link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans+JP:wght@400;500;700&family=IBM+Plex+Mono:wght@400;600&display=swap" rel="stylesheet">
103
+ <title>${escapeHtml(title)}</title>
84
104
  <style>
85
105
  ${css}
86
106
  </style>
@@ -117,20 +137,40 @@ ${html}
117
137
  </html>`;
118
138
  }
119
139
 
120
- async function htmlToPdf(chrome, htmlFile, pdfPath) {
121
- const userDataDir = path.join(os.tmpdir(), `marp-chrome-${process.pid}-${Date.now()}`);
122
- const args = [
123
- '--headless',
124
- '--disable-gpu',
125
- '--no-sandbox',
126
- '--no-pdf-header-footer',
127
- '--virtual-time-budget=8000', // Webフォント読み込みを待つ
140
+ // Chrome の起動引数。サンドボックスは既定で有効のまま。
141
+ // root で動かすコンテナなどサンドボックスが使えない環境だけ、利用者が
142
+ // MARP_CHROME_NO_SANDBOX=1 を設定して外す(サーバーが勝手に外さない)。
143
+ export function chromeArgs({ htmlFile, pdfPath, userDataDir, allowRemote = false, env = process.env }) {
144
+ const args = ['--headless', '--disable-gpu', '--no-pdf-header-footer'];
145
+ if (env.MARP_CHROME_NO_SANDBOX === '1') args.push('--no-sandbox');
146
+ if (!allowRemote) {
147
+ // 外部への通信を止める(名前解決を全部失敗させ、IP直書きも届かないプロキシへ向ける)。
148
+ // file:// で開くローカルの HTML と、その中に埋め込んだデータは影響を受けない。
149
+ args.push('--host-resolver-rules=MAP * ~NOTFOUND', '--proxy-server=127.0.0.1:9', '--proxy-bypass-list=<-loopback>');
150
+ }
151
+ args.push(
152
+ '--virtual-time-budget=8000', // 画像の読み込みを待つ
128
153
  `--user-data-dir=${userDataDir}`,
129
154
  `--print-to-pdf=${pdfPath}`,
130
155
  pathToFileURL(htmlFile).href,
131
- ];
156
+ );
157
+ return args;
158
+ }
159
+
160
+ async function htmlToPdf(chrome, htmlFile, pdfPath, { allowRemote } = {}) {
161
+ const userDataDir = path.join(os.tmpdir(), `marp-chrome-${process.pid}-${Date.now()}`);
162
+ const args = chromeArgs({ htmlFile, pdfPath, userDataDir, allowRemote });
132
163
  try {
133
164
  await execFileP(chrome, args, { timeout: 60000, maxBuffer: 16 * 1024 * 1024 });
165
+ } catch (e) {
166
+ const msg = String((e && (e.stderr || e.message)) || e);
167
+ if (/sandbox/i.test(msg)) {
168
+ throw new Error(
169
+ 'Chrome をサンドボックス付きで起動できませんでした(root で動かすコンテナ等)。' +
170
+ 'この環境で使う場合は、利用者の判断で環境変数 MARP_CHROME_NO_SANDBOX=1 を設定してください。',
171
+ );
172
+ }
173
+ throw e;
134
174
  } finally {
135
175
  await rm(userDataDir, { recursive: true, force: true }).catch(() => {});
136
176
  }
@@ -143,8 +183,10 @@ async function htmlToPdf(chrome, htmlFile, pdfPath) {
143
183
  * @param {object} opts
144
184
  * - theme {string} 'firstch'(既定)/ 'default' / 'gaia' / 'uncover'。md内 theme 指示が優先される
145
185
  * - formats {string[]} ['html'] 既定。'html' / 'pdf' を指定
146
- * - outputPath {string} 出力ファイルのベースパス(拡張子は format 側で決まる)。省略時は tmp
147
- * - title {string} HTML の <title>(既定 'Marp slides')
186
+ * - outputPath {string} 出力ファイルのベースパス(拡張子は format 側で決まる)。省略時は OS の一時ディレクトリ下の firstch-tools-mcp/
187
+ * - title {string} HTML の <title>(既定 'Marp slides'・エスケープして入れる)
188
+ * - overwrite {boolean} 既存ファイルを上書きするか(既定 false=同名があればエラー)
189
+ * - allowRemote {boolean} Markdown が参照する外部の画像・CSS を読むか(既定 false=外へ通信しない)
148
190
  * @returns {Promise<object>} { theme, slides, size, outputs: {html?, pdf?}, pdf_skipped? }
149
191
  */
150
192
  export async function renderMarp(markdown, opts = {}) {
@@ -160,16 +202,23 @@ export async function renderMarp(markdown, opts = {}) {
160
202
  if (f !== 'html' && f !== 'pdf') throw new Error(`未対応の format: ${f}(html / pdf のみ)`);
161
203
  }
162
204
 
205
+ const overwrite = opts.overwrite === true;
206
+ const allowRemote = opts.allowRemote === true;
163
207
  const base = opts.outputPath
164
208
  ? opts.outputPath.replace(/\.(html?|pdf)$/i, '')
165
- : path.join(os.tmpdir(), `marp-${process.pid}-${Date.now()}`);
209
+ : path.join(await defaultOutputDir(), `marp-${process.pid}-${Date.now()}`);
166
210
  const title = opts.title || 'Marp slides';
167
211
 
168
212
  // marp-core は html:false(marp-cli既定と同じ)で生HTML注入を無効化。ディレクティブ用コメントは有効。
169
- const marp = new Marp({ html: false });
213
+ // 絵文字は CDN の画像へ置き換えない(文字のまま)。
214
+ const marp = new Marp({ html: false, emoji: { shortcode: true, unicode: false } });
170
215
  marp.themeSet.add(await firstchThemeCss());
171
216
  marp.themeSet.default = marp.themeSet.get(theme);
172
- const { html, css } = marp.render(markdown);
217
+ const rendered = marp.render(markdown);
218
+ const html = rendered.html;
219
+ let css = rendered.css;
220
+ let removedImports = [];
221
+ if (!allowRemote) ({ css, removed: removedImports } = stripRemoteImports(css));
173
222
 
174
223
  const slides = (html.match(/<section id=/g) || []).length;
175
224
  const size = slideSize(html, css);
@@ -180,13 +229,16 @@ export async function renderMarp(markdown, opts = {}) {
180
229
  const wantPdf = formats.includes('pdf');
181
230
 
182
231
  let htmlForPrint;
232
+ // PDF は Chrome が書くので、上書きの確認を先に済ませる
233
+ if (wantPdf && !overwrite && existsSync(`${base}.pdf`)) throw new OutputExistsError(`${base}.pdf`);
183
234
  if (wantHtml) {
184
235
  outputs.html = `${base}.html`;
185
- await writeFile(outputs.html, doc);
236
+ await writeOutput(outputs.html, doc, { overwrite });
186
237
  htmlForPrint = outputs.html;
187
238
  }
188
239
 
189
240
  const result = { theme, slides, size, outputs };
241
+ if (removedImports.length) result.removed_remote_imports = removedImports;
190
242
 
191
243
  if (wantPdf) {
192
244
  const chrome = findChrome();
@@ -205,7 +257,7 @@ export async function renderMarp(markdown, opts = {}) {
205
257
  }
206
258
  try {
207
259
  outputs.pdf = `${base}.pdf`;
208
- await htmlToPdf(chrome, htmlForPrint, outputs.pdf);
260
+ await htmlToPdf(chrome, htmlForPrint, outputs.pdf, { allowRemote });
209
261
  } catch (e) {
210
262
  delete outputs.pdf;
211
263
  result.pdf_skipped = `PDF生成に失敗しました: ${String(e.message || e)}`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@first-ch/tools-mcp",
3
- "version": "0.34.0",
3
+ "version": "0.36.0",
4
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クローラーの許可プリセット付き)・文字列のケース変換(camelCase/snake_case/kebab-case など11形式)・CSV/TSVとJSON配列の相互変換(区切りの自動判定・a.b 列と入れ子の相互展開)・全角⇄半角の変換とテキストの掃除(文字種ごとの向き指定・半角カナの合成/分解・空白と空行の整理)・IPアドレス/CIDRの計算(ネットワーク・ブロードキャスト・ホスト範囲とホスト数・IPv4/IPv6・サブネット分割・包含判定・IP範囲→最小CIDR集合の逆算)・日数/営業日の計算(2日付間の日数と営業日数・起点日+N日/N営業日の期日・締め日と支払サイトからの支払日・土日と日本の祝日を内蔵)・HTML→Markdownの変換(見出し/リスト/表/リンク/画像/コード・script/styleや装飾タグの除去・本文だけの抽出・相対URLの絶対化)・和暦⇄西暦の変換(令和〜明治・自動判定・曜日と干支・存在しない和暦の指摘・満年齢と入学/卒業の年・元号一覧と早見表)・日本語タイトルからのURLスラッグ生成(かな→ヘボン式ローマ字・記号除去・ハイフン/アンダースコア連結・小文字化・長音の省略/表記))をMCPツールとして提供するサーバー",
5
5
  "type": "module",
6
6
  "bin": {
@@ -13,10 +13,10 @@
13
13
  },
14
14
  "dependencies": {
15
15
  "@marp-team/marp-core": "^4.4.0",
16
- "@modelcontextprotocol/sdk": "^1.0.0",
16
+ "@modelcontextprotocol/server": "^2.3.1",
17
17
  "jpeg-js": "^0.4.4",
18
18
  "pngjs": "^7.0.0",
19
- "zod": "^3.23.0"
19
+ "zod": "^4.2.0"
20
20
  },
21
21
  "license": "MIT",
22
22
  "mcpName": "io.github.First-CH/tools-mcp",
@@ -212,6 +212,7 @@
212
212
  "files": [
213
213
  "server.mjs",
214
214
  "lib.mjs",
215
+ "fs-safe.mjs",
215
216
  "webp.mjs",
216
217
  "marp.mjs",
217
218
  "marp-theme.css",
@@ -246,5 +247,8 @@
246
247
  "vendor/",
247
248
  "README.md",
248
249
  "LICENSE"
249
- ]
250
+ ],
251
+ "overrides": {
252
+ "@xmldom/xmldom": "0.9.12"
253
+ }
250
254
  }
package/px-rem.mjs CHANGED
@@ -3,7 +3,8 @@
3
3
  // 「変換コア」ブロックは site 側の site/px-rem/app.js と同一の実装。
4
4
  // 2箇所ルール: 片方を直したらもう片方も同じ内容で直す(site側が正本)。
5
5
  // 使っているのは Number/String/RegExp だけなので、ブラウザ版のコードをそのまま持ってこられる。
6
- import { readFile, writeFile } from 'node:fs/promises';
6
+ import { readFile } from 'node:fs/promises';
7
+ import { writeOutput } from './fs-safe.mjs';
7
8
  import { basename } from 'node:path';
8
9
 
9
10
  /* ==================== ここから変換コア(site / MCP で同一) ==================== */
@@ -432,7 +433,7 @@ export async function pxRemConvert(opts = {}) {
432
433
  notes,
433
434
  };
434
435
  if (opts.outputPath) {
435
- await writeFile(opts.outputPath, r.text, 'utf8');
436
+ await writeOutput(opts.outputPath, r.text, { overwrite: opts.overwrite });
436
437
  result.output = opts.outputPath;
437
438
  // ファイルに書けたなら本文は重複した重い情報でしかない
438
439
  delete result.text;
package/qr.mjs CHANGED
@@ -6,8 +6,8 @@
6
6
  // そのまま持ってこられる(PNGの書き出しだけは Node に Canvas が無いため pngjs を使う)。
7
7
  // 実装は JIS X 0510 / ISO 18004 に沿っており、型番1〜40・誤り訂正レベル L/M/Q/H・
8
8
  // 数字/英数字/バイト(UTF-8)モードに対応する。
9
- import { writeFile } from 'node:fs/promises';
10
9
  import { PNG } from 'pngjs';
10
+ import { writeOutput } from './fs-safe.mjs';
11
11
 
12
12
  export class QrError extends Error {}
13
13
 
@@ -719,7 +719,7 @@ export async function qrGenerateTool(opts = {}) {
719
719
  if (format === 'png') {
720
720
  const buf = qrMatrixToPng(qr, { size, margin });
721
721
  if (opts.outputPath) {
722
- await writeFile(opts.outputPath, buf);
722
+ await writeOutput(opts.outputPath, buf, { overwrite: opts.overwrite });
723
723
  result.output = opts.outputPath;
724
724
  result.bytes = buf.length;
725
725
  } else {
@@ -732,7 +732,7 @@ export async function qrGenerateTool(opts = {}) {
732
732
 
733
733
  const body = format === 'text' ? qrMatrixToText(qr, { margin }) : qrMatrixToSvg(qr, { size, margin });
734
734
  if (opts.outputPath) {
735
- await writeFile(opts.outputPath, body, 'utf8');
735
+ await writeOutput(opts.outputPath, body, { overwrite: opts.overwrite });
736
736
  result.output = opts.outputPath;
737
737
  result.bytes = Buffer.byteLength(body);
738
738
  } else if (format === 'text') {
package/robots-txt.mjs CHANGED
@@ -417,8 +417,8 @@ export function buildRobotsTxt(config) {
417
417
 
418
418
  /* ==================== MCPツールの入口(site側には無い) ==================== */
419
419
 
420
- import { writeFile } from 'node:fs/promises';
421
420
  import path from 'node:path';
421
+ import { writeOutput } from './fs-safe.mjs';
422
422
 
423
423
  const AI_PURPOSES = ['training', 'search', 'user'];
424
424
 
@@ -496,7 +496,7 @@ export async function robotsTxtGenerate(opts = {}) {
496
496
 
497
497
  if (opts.outputPath) {
498
498
  if (!path.isAbsolute(opts.outputPath)) throw new Error('outputPath は絶対パスで指定してください');
499
- await writeFile(opts.outputPath, result.text, 'utf8');
499
+ await writeOutput(opts.outputPath, result.text, { overwrite: opts.overwrite });
500
500
  return { written: opts.outputPath, warnings: result.warnings, stats: result.stats, ai: result.ai };
501
501
  }
502
502
  return result;
package/server.mjs CHANGED
@@ -1,10 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  // First CH Tools MCP サーバー(stdio)
3
3
  // 導入例: npx -y @first-ch/tools-mcp
4
- import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
5
- import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
+ import { McpServer } from '@modelcontextprotocol/server';
5
+ import { serveStdio } from '@modelcontextprotocol/server/stdio';
6
6
  import { z } from 'zod';
7
- import { appendFile, writeFile } from 'node:fs/promises';
7
+ import { appendFile } from 'node:fs/promises';
8
+ import { writeOutput } from './fs-safe.mjs';
8
9
  import { createRequire } from 'node:module';
9
10
  import { contrastCheck, countChars, buildLlmsTxt, buildJsonLd, analyzeEncoding, convertEncoding } from './lib.mjs';
10
11
  import { generateTestData, FIELDS, DEFAULT_FIELDS, PRESETS } from './testdata.mjs';
@@ -38,7 +39,49 @@ import { warekiConvertTool } from './wareki.mjs';
38
39
  import { slugGenerateTool } from './slug.mjs';
39
40
 
40
41
  const { version } = createRequire(import.meta.url)('./package.json');
41
- const server = new McpServer({ name: 'firstch-tools', version });
42
+ // SDK v2 の serveStdio は接続ごとに factory から McpServer を1つ作る(旧仕様の initialize と
43
+ // 2026-07-28 仕様の server/discover の両方を、同じ登録内容で受ける)。ツールは下の registerTool で
44
+ // 一覧に積み、buildServer() が接続のたびに登録する。
45
+ const TOOLS = [];
46
+ function buildServer() {
47
+ const server = new McpServer({ name: 'firstch-tools', version }, { capabilities: { tools: {} } });
48
+ for (const { name, config, handler } of TOOLS) server.registerTool(name, config, handler);
49
+ return server;
50
+ }
51
+
52
+ // ---------------------------------------------------------------------------
53
+ // ツールの注釈(MCP の annotations)
54
+ // クライアントが「読むだけか・ファイルを書き換えうるか・外部と通信するか」を判断できるよう、
55
+ // 全ツールに付ける。ファイルを書き出す引数(outputPath / outputDir)を持つツールと、
56
+ // 常にファイルを書くツール(webp_convert・marp_render)は readOnlyHint: false・destructiveHint: true
57
+ // (overwrite: true を渡すと既存ファイルを上書きしうるため)。既定では上書きしない。
58
+ // それ以外は手元で計算する(または利用者が指定したファイルを読む)だけなので readOnlyHint: true。
59
+ // 外部と通信しうるのは marp_render の allowRemote: true のときだけ。
60
+ // ---------------------------------------------------------------------------
61
+ const ALWAYS_WRITES = new Set(['webp_convert', 'marp_render']);
62
+ const OPEN_WORLD = new Set(['marp_render']);
63
+
64
+ function toolAnnotations(name, inputSchema = {}) {
65
+ const writes = ALWAYS_WRITES.has(name) || 'outputPath' in inputSchema || 'outputDir' in inputSchema;
66
+ const openWorldHint = OPEN_WORLD.has(name);
67
+ if (!writes) return { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint };
68
+ return { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint };
69
+ }
70
+
71
+ const OVERWRITE_PARAM = z
72
+ .boolean()
73
+ .optional()
74
+ .describe('出力先に同名のファイルがあるとき上書きするか(既定 false=上書きせずエラーにする)');
75
+
76
+ function registerTool(name, config, handler) {
77
+ let inputSchema = config.inputSchema || {};
78
+ const annotations = { title: config.title, ...toolAnnotations(name, inputSchema) };
79
+ if (!annotations.readOnlyHint && !('overwrite' in inputSchema)) {
80
+ inputSchema = { ...inputSchema, overwrite: OVERWRITE_PARAM };
81
+ }
82
+ // v2 は Standard Schema を求めるため、引数の形(shape)を z.object で包んで渡す
83
+ TOOLS.push({ name, config: { ...config, inputSchema: z.object(inputSchema), annotations }, handler });
84
+ }
42
85
 
43
86
  const asText = (obj) => ({ content: [{ type: 'text', text: JSON.stringify(obj, null, 2) }] });
44
87
 
@@ -51,7 +94,7 @@ const logUsage = (tool) =>
51
94
  ? appendFile(USAGE_LOG, JSON.stringify({ ts: new Date().toISOString(), tool, source: 'mcp' }) + '\n').catch(() => {})
52
95
  : Promise.resolve();
53
96
 
54
- server.registerTool(
97
+ registerTool(
55
98
  'contrast_check',
56
99
  {
57
100
  title: 'WCAGコントラスト比チェック',
@@ -69,7 +112,7 @@ server.registerTool(
69
112
  },
70
113
  );
71
114
 
72
- server.registerTool(
115
+ registerTool(
73
116
  'count_chars',
74
117
  {
75
118
  title: '文字数カウント(Xウェイト対応)',
@@ -86,7 +129,7 @@ server.registerTool(
86
129
  },
87
130
  );
88
131
 
89
- server.registerTool(
132
+ registerTool(
90
133
  'webp_convert',
91
134
  {
92
135
  title: '画像→WebP変換',
@@ -100,14 +143,14 @@ server.registerTool(
100
143
  outputDir: z.string().optional().describe('出力先ディレクトリ(省略時は各入力と同じ場所)'),
101
144
  },
102
145
  },
103
- async ({ paths, quality, outputDir }) => {
146
+ async ({ paths, quality, outputDir, overwrite }) => {
104
147
  await logUsage('webp_convert');
105
148
  const { join, basename } = await import('node:path');
106
149
  const results = [];
107
150
  for (const p of paths) {
108
151
  try {
109
152
  const output = outputDir ? join(outputDir, basename(p).replace(/\.[^.]+$/, '') + '.webp') : undefined;
110
- results.push(await convertToWebp(p, { quality, output }));
153
+ results.push(await convertToWebp(p, { quality, output, overwrite }));
111
154
  } catch (e) {
112
155
  results.push({ input: p, error: String(e.message || e) });
113
156
  }
@@ -116,7 +159,7 @@ server.registerTool(
116
159
  },
117
160
  );
118
161
 
119
- server.registerTool(
162
+ registerTool(
120
163
  'jsonld_generate',
121
164
  {
122
165
  title: 'JSON-LD構造化データ生成',
@@ -166,7 +209,7 @@ server.registerTool(
166
209
  },
167
210
  );
168
211
 
169
- server.registerTool(
212
+ registerTool(
170
213
  'llmstxt_generate',
171
214
  {
172
215
  title: 'llms.txt 生成',
@@ -200,7 +243,7 @@ server.registerTool(
200
243
  },
201
244
  );
202
245
 
203
- server.registerTool(
246
+ registerTool(
204
247
  'encoding_convert',
205
248
  {
206
249
  title: '文字コード・改行コード変換',
@@ -210,7 +253,7 @@ server.registerTool(
210
253
  'リポジトリ内ファイルの改行コード事故(CRLFがLFに書き換わる等)の確認に使う。' +
211
254
  'mode=analyze なら判定のみ、mode=convert なら変換後のテキストとbase64を返す。',
212
255
  inputSchema: {
213
- base64: z.string().describe('対象ファイルの内容(base64)。テキストを直接渡す場合は text を使う'),
256
+ base64: z.string().optional().describe('対象ファイルの内容(base64)。テキストを直接渡す場合は text を使う(どちらか必須)'),
214
257
  text: z.string().optional().describe('base64の代わりにテキストを直接渡す場合(UTF-8として扱う)'),
215
258
  mode: z.enum(['analyze', 'convert']).optional().describe('既定 analyze。convert で変換結果を返す'),
216
259
  encoding: z.enum(['utf-8', 'shift_jis']).optional().describe('入力の文字コード。省略時は自動判定'),
@@ -230,17 +273,22 @@ server.registerTool(
230
273
  },
231
274
  );
232
275
 
233
- server.registerTool(
276
+ registerTool(
234
277
  'marp_render',
235
278
  {
236
279
  title: 'Marp Markdown→スライド レンダリング',
237
280
  description:
238
281
  'Marp Markdown をスライドへレンダリングし、HTML(テーマCSSをインラインした自己完結ファイル)や PDF を書き出す。' +
239
282
  'AIが生成したスライド用Markdownをそのまま渡せば描画まで完結する(社内の marp ビルドの定型化・顧客配布資料の生成に使う)。' +
240
- '和文テーマ firstch(firstch-design 準拠・紙/墨/朱・IBM Plex Sans JP)を同梱し、既定テーマにする。' +
283
+ '和文テーマ firstch(紙/墨/朱・IBM Plex Sans JP が入っていれば使う)を同梱し、既定テーマにする。' +
241
284
  'Markdown 側の Marp フロントマター(例: theme:/paginate:/size:/`<!-- _class: lead -->`)はそのまま効く。' +
242
285
  'PDF はローカルの Chrome/Chromium を headless で呼び出して生成する(未検出なら HTML のみ返し理由を添える。' +
243
- '環境変数 MARP_CHROME_PATH で実行ファイルを明示可)。完全ローカル処理・ネットワーク送信なし。',
286
+ '環境変数 MARP_CHROME_PATH で実行ファイルを明示可)。' +
287
+ '既定では外部へ通信しない(Webフォントを読まず、絵文字は文字のまま、組み込みテーマの外部フォント @import は取り除き、' +
288
+ 'PDF を作る Chrome も外部への通信を止めて起動する)。Markdown が参照する外部の画像・CSS を PDF に入れたいときだけ allowRemote: true を渡す。' +
289
+ '出力した HTML を利用者がブラウザで開いたときは、Markdown に書いた外部画像をそのブラウザが読み込む。' +
290
+ 'ファイルを書き出す(outputPath・inputPath と同じ場所、どちらも無ければ OS の一時ディレクトリ下の firstch-tools-mcp/)。' +
291
+ '同名のファイルがあれば上書きせずエラーにする(上書きは overwrite: true)。書き出したファイルは消さない。',
244
292
  inputSchema: {
245
293
  markdown: z.string().optional().describe('Marp Markdown 本文(inputPath と排他・どちらか必須)'),
246
294
  inputPath: z.string().optional().describe('Markdownファイルの絶対パス(markdown 未指定時に読み込む)'),
@@ -257,9 +305,13 @@ server.registerTool(
257
305
  .optional()
258
306
  .describe('出力ファイルのベースパス(拡張子は自動。省略時は inputPath 準拠、無ければ一時ディレクトリ)'),
259
307
  title: z.string().optional().describe('HTML の <title>(既定 "Marp slides")'),
308
+ allowRemote: z
309
+ .boolean()
310
+ .optional()
311
+ .describe('Markdown が参照する外部の画像・CSS を読み込むか(既定 false=外部へ通信しない)'),
260
312
  },
261
313
  },
262
- async ({ markdown, inputPath, theme, formats, outputPath, title }) => {
314
+ async ({ markdown, inputPath, theme, formats, outputPath, title, overwrite, allowRemote }) => {
263
315
  await logUsage('marp_render');
264
316
  let md = markdown;
265
317
  let outBase = outputPath;
@@ -272,11 +324,11 @@ server.registerTool(
272
324
  if (!docTitle) docTitle = basename(inputPath, extname(inputPath));
273
325
  }
274
326
  if (md === undefined || md === '') throw new Error('markdown か inputPath のどちらかが必要です');
275
- return asText(await renderMarp(md, { theme, formats, outputPath: outBase, title: docTitle }));
327
+ return asText(await renderMarp(md, { theme, formats, outputPath: outBase, title: docTitle, overwrite, allowRemote }));
276
328
  },
277
329
  );
278
330
 
279
- server.registerTool(
331
+ registerTool(
280
332
  'testdata_generate',
281
333
  {
282
334
  title: 'テストデータ生成(ダミーCSV/JSON/Excel・境界値テキスト)',
@@ -310,7 +362,7 @@ server.registerTool(
310
362
  await logUsage('testdata_generate');
311
363
  const { _bytes, ...result } = generateTestData(opts);
312
364
  if (opts.outputPath && result.mode === 'records') {
313
- await writeFile(opts.outputPath, _bytes);
365
+ await writeOutput(opts.outputPath, _bytes, { overwrite: opts.overwrite });
314
366
  result.output = opts.outputPath;
315
367
  // ファイルに書けたなら base64 は重複した重い情報でしかない
316
368
  delete result.base64;
@@ -319,7 +371,7 @@ server.registerTool(
319
371
  },
320
372
  );
321
373
 
322
- server.registerTool(
374
+ registerTool(
323
375
  'diff_check',
324
376
  {
325
377
  title: 'テキスト・コード差分チェック',
@@ -374,7 +426,7 @@ server.registerTool(
374
426
  },
375
427
  );
376
428
 
377
- server.registerTool(
429
+ registerTool(
378
430
  'cron_explain',
379
431
  {
380
432
  title: 'Cron式の解説+次回発火日時',
@@ -401,7 +453,7 @@ server.registerTool(
401
453
  },
402
454
  );
403
455
 
404
- server.registerTool(
456
+ registerTool(
405
457
  'base64_encode',
406
458
  {
407
459
  title: 'Base64 / Data URI エンコード・デコード',
@@ -435,7 +487,7 @@ server.registerTool(
435
487
  },
436
488
  );
437
489
 
438
- server.registerTool(
490
+ registerTool(
439
491
  'url_params',
440
492
  {
441
493
  title: 'URLパラメータの分解・編集・再構築',
@@ -462,7 +514,7 @@ server.registerTool(
462
514
  .enum(['component', 'uri', 'form'])
463
515
  .optional()
464
516
  .describe('encode/decode の方式(既定 component=encodeURIComponent / uri=encodeURI / form=スペースを +)'),
465
- set: z.record(z.string()).optional().describe('parse: 追加・上書きするパラメータ(値が空文字なら削除)'),
517
+ set: z.record(z.string(), z.string()).optional().describe('parse: 追加・上書きするパラメータ(値が空文字なら削除)'),
466
518
  remove: z.array(z.string()).optional().describe('parse: 削除するパラメータ名(大文字小文字を無視)'),
467
519
  utm: z
468
520
  .record(z.string())
@@ -480,7 +532,7 @@ server.registerTool(
480
532
  },
481
533
  );
482
534
 
483
- server.registerTool(
535
+ registerTool(
484
536
  'html_escape',
485
537
  {
486
538
  title: 'HTML特殊文字のエスケープ・エンティティのデコード',
@@ -525,7 +577,7 @@ const JSON_YAML_SHARED =
525
577
  '設定ファイルの構文チェックにも使える。' +
526
578
  '読み替えで意味が変わる箇所は notes で知らせる(キーの重複=後が勝つ・2の53乗を超える整数の桁落ちなど)。';
527
579
 
528
- server.registerTool(
580
+ registerTool(
529
581
  'json_to_yaml',
530
582
  {
531
583
  title: 'JSON → YAML 変換・整形',
@@ -563,7 +615,7 @@ server.registerTool(
563
615
  },
564
616
  );
565
617
 
566
- server.registerTool(
618
+ registerTool(
567
619
  'yaml_to_json',
568
620
  {
569
621
  title: 'YAML → JSON 変換・構文チェック',
@@ -599,7 +651,7 @@ server.registerTool(
599
651
  },
600
652
  );
601
653
 
602
- server.registerTool(
654
+ registerTool(
603
655
  'px_rem_convert',
604
656
  {
605
657
  title: 'px ⇄ rem / em 単位換算・CSSの一括変換',
@@ -662,7 +714,7 @@ server.registerTool(
662
714
  },
663
715
  );
664
716
 
665
- server.registerTool(
717
+ registerTool(
666
718
  'color_convert',
667
719
  {
668
720
  title: 'カラーコード変換・アルファ透過計算',
@@ -706,7 +758,7 @@ server.registerTool(
706
758
  },
707
759
  );
708
760
 
709
- server.registerTool(
761
+ registerTool(
710
762
  'hash_generate',
711
763
  {
712
764
  title: 'MD5 / SHA-1 / SHA-256 / SHA-384 / SHA-512 ハッシュ生成・照合',
@@ -749,7 +801,7 @@ server.registerTool(
749
801
  },
750
802
  );
751
803
 
752
- server.registerTool(
804
+ registerTool(
753
805
  'jwt_decode',
754
806
  {
755
807
  title: 'JWTのデコード・有効期限チェック・署名の検証',
@@ -786,7 +838,7 @@ server.registerTool(
786
838
  },
787
839
  );
788
840
 
789
- server.registerTool(
841
+ registerTool(
790
842
  'user_agent_parse',
791
843
  {
792
844
  title: 'User-Agent文字列の解析とデバイス判定',
@@ -824,7 +876,7 @@ server.registerTool(
824
876
  },
825
877
  );
826
878
 
827
- server.registerTool(
879
+ registerTool(
828
880
  'uuid_generate',
829
881
  {
830
882
  title: 'UUID v4 / ULID の一括生成',
@@ -863,7 +915,7 @@ server.registerTool(
863
915
  },
864
916
  );
865
917
 
866
- server.registerTool(
918
+ registerTool(
867
919
  'aspect_ratio_calc',
868
920
  {
869
921
  title: 'アスペクト比の計算・レスポンシブサイズ算出',
@@ -924,7 +976,7 @@ server.registerTool(
924
976
  },
925
977
  );
926
978
 
927
- server.registerTool(
979
+ registerTool(
928
980
  'markdown_table',
929
981
  {
930
982
  title: 'TSV/CSV → Markdownテーブル整形・相互変換',
@@ -982,7 +1034,7 @@ server.registerTool(
982
1034
  },
983
1035
  );
984
1036
 
985
- server.registerTool(
1037
+ registerTool(
986
1038
  'sql_format',
987
1039
  {
988
1040
  title: 'SQLクエリの整形(予約語の大文字化・句ごとの改行・字下げ)',
@@ -1034,7 +1086,7 @@ server.registerTool(
1034
1086
  },
1035
1087
  );
1036
1088
 
1037
- server.registerTool(
1089
+ registerTool(
1038
1090
  'qr_generate',
1039
1091
  {
1040
1092
  title: 'QRコードの生成(SVG / PNG / 文字の図)',
@@ -1076,7 +1128,7 @@ server.registerTool(
1076
1128
  },
1077
1129
  );
1078
1130
 
1079
- server.registerTool(
1131
+ registerTool(
1080
1132
  'unixtime_convert',
1081
1133
  {
1082
1134
  title: 'UNIXタイムスタンプ⇄日時の相互変換',
@@ -1121,7 +1173,7 @@ server.registerTool(
1121
1173
  },
1122
1174
  );
1123
1175
 
1124
- server.registerTool(
1176
+ registerTool(
1125
1177
  'robotstxt_generate',
1126
1178
  {
1127
1179
  title: 'robots.txt の生成(AIクローラー対応)',
@@ -1168,7 +1220,7 @@ server.registerTool(
1168
1220
  .object({
1169
1221
  preset: z.enum(['allow', 'block', 'training', 'none', 'custom']).optional()
1170
1222
  .describe("AIクローラーのプリセット(既定 'training'=学習目的だけ拒否)"),
1171
- overrides: z.record(z.enum(['allow', 'block', 'omit'])).optional()
1223
+ overrides: z.record(z.string(), z.enum(['allow', 'block', 'omit'])).optional()
1172
1224
  .describe("1件ずつの指定(例: {\"GPTBot\": \"block\", \"PerplexityBot\": \"allow\"})"),
1173
1225
  inherit: z.boolean().optional()
1174
1226
  .describe('共通の禁止パスを許可したAIクローラーのグループへ書き写すか(既定 true)'),
@@ -1203,7 +1255,7 @@ server.registerTool(
1203
1255
  },
1204
1256
  );
1205
1257
 
1206
- server.registerTool(
1258
+ registerTool(
1207
1259
  'case_convert',
1208
1260
  {
1209
1261
  title: '文字列のケース変換(camelCase / snake_case / kebab-case)',
@@ -1248,7 +1300,7 @@ server.registerTool(
1248
1300
  },
1249
1301
  );
1250
1302
 
1251
- server.registerTool(
1303
+ registerTool(
1252
1304
  'csv_convert',
1253
1305
  {
1254
1306
  title: 'CSV/TSV ⇄ JSON の相互変換',
@@ -1297,7 +1349,7 @@ server.registerTool(
1297
1349
  },
1298
1350
  );
1299
1351
 
1300
- server.registerTool(
1352
+ registerTool(
1301
1353
  'zenkaku_convert',
1302
1354
  {
1303
1355
  title: '全角⇄半角の変換とテキストの掃除',
@@ -1349,7 +1401,7 @@ server.registerTool(
1349
1401
  },
1350
1402
  );
1351
1403
 
1352
- server.registerTool(
1404
+ registerTool(
1353
1405
  'cidr_calc',
1354
1406
  {
1355
1407
  title: 'IPアドレス・CIDRの計算',
@@ -1386,7 +1438,7 @@ server.registerTool(
1386
1438
  },
1387
1439
  );
1388
1440
 
1389
- server.registerTool(
1441
+ registerTool(
1390
1442
  'date_calc',
1391
1443
  {
1392
1444
  title: '日数・営業日の計算',
@@ -1432,7 +1484,7 @@ server.registerTool(
1432
1484
  },
1433
1485
  );
1434
1486
 
1435
- server.registerTool(
1487
+ registerTool(
1436
1488
  'html_to_markdown',
1437
1489
  {
1438
1490
  title: 'HTML → Markdown 変換',
@@ -1481,7 +1533,7 @@ server.registerTool(
1481
1533
  },
1482
1534
  );
1483
1535
 
1484
- server.registerTool(
1536
+ registerTool(
1485
1537
  'wareki_convert',
1486
1538
  {
1487
1539
  title: '和暦 ⇄ 西暦変換・満年齢',
@@ -1517,7 +1569,7 @@ server.registerTool(
1517
1569
  },
1518
1570
  );
1519
1571
 
1520
- server.registerTool(
1572
+ registerTool(
1521
1573
  'slug_generate',
1522
1574
  {
1523
1575
  title: 'URLスラッグ生成(日本語タイトル→ローマ字)',
@@ -1553,4 +1605,4 @@ server.registerTool(
1553
1605
  },
1554
1606
  );
1555
1607
 
1556
- await server.connect(new StdioServerTransport());
1608
+ serveStdio(buildServer);
package/sql-format.mjs CHANGED
@@ -3,7 +3,8 @@
3
3
  // 「整形コア」ブロックは site 側の site/sql-format/app.js と同一の実装。
4
4
  // 2箇所ルール: 片方を直したらもう片方も同じ内容で直す(site側が正本)。
5
5
  // 使っているのは String/RegExp/Array/Set だけなので、ブラウザ版のコードをそのまま持ってこられる。
6
- import { readFile, writeFile } from 'node:fs/promises';
6
+ import { readFile } from 'node:fs/promises';
7
+ import { writeOutput } from './fs-safe.mjs';
7
8
  import { basename } from 'node:path';
8
9
 
9
10
  /* ==================== ここから整形コア(site / MCP で同一) ==================== */
@@ -685,7 +686,7 @@ export async function sqlFormatTool(opts = {}) {
685
686
  notes: r.notes.map((n) => ({ code: n.code, message: noteMessage(n) })),
686
687
  };
687
688
  if (opts.outputPath) {
688
- await writeFile(opts.outputPath, r.text, 'utf8');
689
+ await writeOutput(opts.outputPath, r.text, { overwrite: opts.overwrite });
689
690
  result.output = opts.outputPath;
690
691
  // ファイルに書けたなら本文は重複した重い情報でしかない
691
692
  delete result.text;
package/webp.mjs CHANGED
@@ -4,7 +4,8 @@
4
4
  // =ブラウザ版と同一品質・同一アルゴリズム。
5
5
  // PNG/JPEG のデコードのみ Node に Canvas がないため pure-JS の pngjs / jpeg-js で行う。
6
6
 
7
- import { readFile, writeFile } from 'node:fs/promises';
7
+ import { readFile } from 'node:fs/promises';
8
+ import { writeOutput } from './fs-safe.mjs';
8
9
  import path from 'node:path';
9
10
  import { PNG } from 'pngjs';
10
11
  import jpeg from 'jpeg-js';
@@ -42,7 +43,7 @@ function decodeImage(buf, file) {
42
43
  /**
43
44
  * 1ファイルをWebPへ変換する。
44
45
  * @param {string} input 入力ファイルの絶対パス(PNG/JPEG)
45
- * @param {object} opts { output?: 出力パス(既定=入力の拡張子を.webpに), quality?: 1-100(既定80・サイト版と同じ) }
46
+ * @param {object} opts { output?: 出力パス(既定=入力の拡張子を.webpに), quality?: 1-100(既定80・サイト版と同じ), overwrite?: 既存ファイルを上書きするか(既定 false) }
46
47
  * @returns {Promise<object>} { input, output, width, height, bytesIn, bytesOut, saving }
47
48
  */
48
49
  export async function convertToWebp(input, opts = {}) {
@@ -54,7 +55,7 @@ export async function convertToWebp(input, opts = {}) {
54
55
  const result = encoder.encode(image.data, image.width, image.height, { ...defaultOptions, quality });
55
56
  if (!result) throw new Error(`${path.basename(input)}: エンコードに失敗しました`);
56
57
  const webp = result.buffer;
57
- await writeFile(output, Buffer.from(webp));
58
+ await writeOutput(output, Buffer.from(webp), { overwrite: opts.overwrite === true });
58
59
  const bytesOut = webp.byteLength;
59
60
  return {
60
61
  input,
package/zenkaku.mjs CHANGED
@@ -3,7 +3,8 @@
3
3
  // 「変換コア」ブロックは site 側の site/zenkaku/app.js と同一の実装。
4
4
  // 2箇所ルール: 片方を直したらもう片方も同じ内容で直す(site側が正本)。
5
5
  // 使っているのは String/RegExp/Map だけなので、ブラウザ版のコードをそのまま持ってこられる。
6
- import { readFile, writeFile } from 'node:fs/promises';
6
+ import { readFile } from 'node:fs/promises';
7
+ import { writeOutput } from './fs-safe.mjs';
7
8
  import { basename } from 'node:path';
8
9
 
9
10
  /* ==================== ここから変換コア(site / MCP で同一) ==================== */
@@ -445,7 +446,7 @@ export async function zenkakuConvertTool(opts = {}) {
445
446
  const i = notes.findIndex((n) => n.code === 'UNCHANGED');
446
447
  if (i !== -1) notes.splice(i, 1);
447
448
  } else if (opts.outputPath) {
448
- await writeFile(opts.outputPath, r.text, 'utf8');
449
+ await writeOutput(opts.outputPath, r.text, { overwrite: opts.overwrite });
449
450
  result.output = opts.outputPath;
450
451
  } else if ([...r.text].length > MAX_TEXT) {
451
452
  result.text = [...r.text].slice(0, MAX_TEXT).join('');