@pecot/visual-mcp 1.3.1 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +12 -12
  3. package/assets/slidev/package.json +1 -1
  4. package/assets/slidev/scripts/eslint/slidev-pages-lint/package.json +1 -1
  5. package/assets/slidev/scripts/eslint/text-constraints/package.json +1 -1
  6. package/cli/dist/commands/drawio/errors.d.ts +5 -4
  7. package/cli/dist/commands/drawio/export.d.ts +6 -5
  8. package/cli/dist/commands/drawio/export.js +0 -2
  9. package/cli/dist/commands/drawio/url.d.ts +2 -1
  10. package/cli/dist/commands/drawio/url.js +0 -1
  11. package/cli/dist/commands/evidence-xlsx/create.d.ts +2 -1
  12. package/cli/dist/commands/evidence-xlsx/create.js +0 -1
  13. package/cli/dist/commands/pptx-ooxml/preview.d.ts +4 -3
  14. package/cli/dist/commands/pptx-ooxml/preview.js +0 -3
  15. package/cli/dist/commands/slidev-project/create.d.ts +2 -1
  16. package/cli/dist/commands/slidev-project/create.js +0 -1
  17. package/cli/dist/commands/slidev-project/lint.d.ts +2 -1
  18. package/cli/dist/commands/slidev-project/sync.d.ts +2 -1
  19. package/cli/dist/commands/slidev-project/sync.js +0 -1
  20. package/cli/dist/commands/slidev-project/theme.d.ts +2 -1
  21. package/cli/dist/commands/slidev-to-pptx/convert.d.ts +6 -5
  22. package/cli/dist/commands/slidev-to-pptx/convert.js +0 -4
  23. package/cli/dist/domain/_shared/failure-kind.d.ts +13 -0
  24. package/cli/dist/domain/_shared/failure-kind.js +103 -0
  25. package/cli/dist/domain/slidev-project/errors.d.ts +5 -4
  26. package/cli/dist/domain/slidev-theme/error-reason.d.ts +9 -5
  27. package/cli/dist/infra/_shared/dependency-root.d.ts +3 -3
  28. package/cli/dist/infra/_shared/dependency-root.js +5 -5
  29. package/cli/dist/infra/_shared/runtime-install.d.ts +1 -1
  30. package/cli/dist/infra/_shared/runtime-install.js +1 -1
  31. package/cli/dist/infra/_shared/slidev-bin.d.ts +1 -1
  32. package/cli/dist/infra/_shared/slidev-bin.js +1 -1
  33. package/cli/dist/infra/playwright/chromium.js +2 -2
  34. package/cli/dist/infra/playwright/host-dependencies.js +1 -1
  35. package/cli/dist/infra/playwright/launch.js +1 -1
  36. package/cli/dist/infra/slidev-to-pptx/pipeline.js +1 -1
  37. package/cli/dist/infra/slidev-to-pptx/runner.js +1 -1
  38. package/cli/dist/mcp/dev-server-registry.d.ts +6 -1
  39. package/cli/dist/mcp/dev-server-registry.js +4 -1
  40. package/cli/dist/mcp/result.d.ts +36 -61
  41. package/cli/dist/mcp/result.js +73 -75
  42. package/cli/dist/mcp/tool-names.d.ts +17 -0
  43. package/cli/dist/mcp/tool-names.js +26 -0
  44. package/cli/dist/mcp/tools/_shared.d.ts +40 -38
  45. package/cli/dist/mcp/tools/_shared.js +63 -72
  46. package/cli/dist/mcp/tools/drawio.js +47 -61
  47. package/cli/dist/mcp/tools/evidence.js +11 -18
  48. package/cli/dist/mcp/tools/setup.d.ts +1 -1
  49. package/cli/dist/mcp/tools/setup.js +18 -38
  50. package/cli/dist/mcp/tools/slide-dev.js +17 -36
  51. package/cli/dist/mcp/tools/slide-page.d.ts +2 -1
  52. package/cli/dist/mcp/tools/slide-page.js +20 -26
  53. package/cli/dist/mcp/tools/slide-theme.js +4 -11
  54. package/cli/dist/mcp/tools/slide.d.ts +2 -2
  55. package/cli/dist/mcp/tools/slide.js +31 -73
  56. package/cli/dist/mcp/warnings.d.ts +24 -0
  57. package/cli/dist/mcp/warnings.js +101 -0
  58. package/cli/dist/mcp/windows-path.js +1 -1
  59. package/npm-shrinkwrap.json +92 -33
  60. package/package.json +2 -2
  61. package/vendor/text-rules/dist/source-hash +1 -1
@@ -2,7 +2,8 @@ import type { Writable } from 'node:stream';
2
2
  import { z } from 'zod';
3
3
  import type { SpawnResult } from '../../domain/_shared/spawn-result.js';
4
4
  import { type RuntimeInstallResult } from '../../infra/_shared/runtime-install.js';
5
- import { type ToolResult } from '../result.js';
5
+ import type { CallToolResult } from '@modelcontextprotocol/server';
6
+ import { type FailedToolResult, type ToolResult } from '../result.js';
6
7
  /**
7
8
  パス型パラメータの description 末尾に足す 1 文 (直前の文は句点で閉じてから連結する)。
8
9
 
@@ -13,20 +14,27 @@ import { type ToolResult } from '../result.js';
13
14
  */
14
15
  export declare const WINDOWS_PATH_NOTE: string;
15
16
  /**
16
- ToolResult 同形の outputSchema。
17
-
18
- data はツールごとに形が異なる (対応 CLI の --json 出力と同形) ため、共通スキーマでは
19
- record として受け、同形性の検証は contract / parity テスト側で行う。
17
+ 全ツール共通の outputSchema。ツールごとの項目は形が違うため開いた object にし、共通の 4 項目だけ名前を持たせる。
20
18
  */
21
19
  export declare const TOOL_OUTPUT_SCHEMA: z.ZodObject<{
22
- ok: z.ZodBoolean;
23
- exitCode: z.ZodNumber;
24
- artifacts: z.ZodArray<z.ZodString>;
25
- data: z.ZodRecord<z.ZodString, z.ZodUnknown>;
26
- message: z.ZodString;
27
- stdout: z.ZodOptional<z.ZodString>;
28
- stderr: z.ZodOptional<z.ZodString>;
29
- }, z.core.$strip>;
20
+ kind: z.ZodOptional<z.ZodString>;
21
+ detail: z.ZodOptional<z.ZodString>;
22
+ log: z.ZodOptional<z.ZodString>;
23
+ warnings: z.ZodOptional<z.ZodArray<z.ZodString>>;
24
+ }, z.core.$loose>;
25
+ /**
26
+ 捕捉した stdout / stderr の文字列。warnings を省くと stderr から取る。
27
+ */
28
+ export interface CapturedText {
29
+ readonly stdout: string;
30
+ readonly stderr: string;
31
+ readonly warnings?: readonly string[];
32
+ }
33
+ /**
34
+ 捕捉した出力を ToolResult の data へ移す。warning の文は warnings へ (既にある文と重ねて重複を除く)、
35
+ 失敗のときは出力の全体を log へ入れる。
36
+ */
37
+ export declare function withCapturedOutput<Result extends ToolResult>(result: Result, captured: Readonly<CapturedText>): Result;
30
38
  export interface CommandOutput {
31
39
  /**
32
40
  既存コマンドの deps.stdout / deps.stderr にそのまま渡す。
@@ -34,44 +42,38 @@ export interface CommandOutput {
34
42
  readonly stdout: Writable;
35
43
  readonly stderr: Writable;
36
44
  /**
37
- 捕捉した内容を ToolResult へ転写する。
38
-
39
- 内容が空でもキーは残す。ToolResult の stdout / stderr が省略されるのは「捕捉していない」
40
- ときで、捕捉した結果が空であることとは意味が違う。
45
+ 捕捉した出力を withCapturedOutput で result の data へ移し、CallToolResult にする。
41
46
  */
42
- part(): Pick<ToolResult, 'stdout' | 'stderr'>;
47
+ finish(result: Readonly<ToolResult>): CallToolResult;
48
+ /**
49
+ 捕捉した stderr の warning の文。finish が warnings へ入れる配列と同じ。message の件数を作るときに使う。
50
+ */
51
+ warnings(): string[];
43
52
  }
44
53
  /**
45
54
  MCP サーバの process.stdout は JSON-RPC 専有なので、コマンドの出力は必ずここへ逃がす。
46
55
  */
47
56
  export declare function captureCommandOutput(): CommandOutput;
48
57
  /**
49
- 子プロセスの結果を ToolResult の stdout / stderr へ載せる形に整える。
50
-
51
- Writable を通さない出力にも、captureCommandOutput と同じ上限をかけるための関数。
52
- 空でもキーを残すのは CommandOutput.part() と同じ契約。
58
+ 子プロセスの出力を result の data へ移す。warning は切り詰める前の stderr の全体から取る。
53
59
  */
54
- export declare function spawnOutputPart(result: Readonly<SpawnResult>): Pick<ToolResult, 'stdout' | 'stderr'>;
60
+ export declare function withSpawnOutput<Result extends ToolResult>(result: Result, spawned: Readonly<SpawnResult>): Result;
55
61
  /**
56
- ツールの失敗 message / data.detail に載せる 1 行の理由。
62
+ ツールの失敗の detail に載せる 1 行の理由。
57
63
  */
58
64
  export declare function formatError(error: unknown): string;
59
65
  /**
60
- 文面の違反で生成を止めたときの message。drawio_create と evidence_create で同じ文言にする。
66
+ 文面の違反で生成を止めたときの直し方。drawio_create と evidence_create で同じ文言にする。
61
67
  */
62
68
  export declare function textViolationMessage(count: number): string;
63
69
  /**
64
- errorData の data から、文面の違反の件数を取る。違反を持たない失敗は undefined。
65
- */
66
- export declare function violationCountOf(data: Readonly<Record<string, unknown>>): number | undefined;
67
- /**
68
- chromium 不在 / 取得失敗で実処理を諦めたときの exit code (各コマンドの RuntimeError と同じ 1)。
70
+ 失敗の detail。文面の違反なら、違反の一覧に直し方の 1 行を足す。
69
71
  */
70
- export declare const CHROMIUM_UNAVAILABLE_EXIT_CODE = 1;
72
+ export declare function failureDetailOf(error: unknown, data: Readonly<Record<string, unknown>>): string;
71
73
  /**
72
- 実行時依存 (永続層) 不在 / 取得失敗で実処理を諦めたときの exit code。
74
+ errorData の data から、文面の違反の件数を取る。違反を持たない失敗は undefined。
73
75
  */
74
- export declare const RUNTIME_UNAVAILABLE_EXIT_CODE = 1;
76
+ export declare function violationCountOf(data: Readonly<Record<string, unknown>>): number | undefined;
75
77
  /**
76
78
  永続層の場所を特定できないときに利用者向けの応答へ載せる既定の表記。
77
79
  */
@@ -106,14 +108,14 @@ chromium を要するツールのハンドラ冒頭で使う実行時ガード (
106
108
 
107
109
  `pecotv mcp` は接続タイムアウト (Claude Code の MCP_TIMEOUT は 30000ms が初期値) に収めるため、
108
110
  起動時に chromium を取得しない。モデルから呼ばれるツールが 120MB のダウンロードを無断で始めないよう、
109
- 初期状態では取得せず、`setup` ツールの呼び出しを案内する。
111
+ 初期状態では取得せず、`runtime_setup` ツールの呼び出しを案内する。
110
112
  PECOTV_AUTO_INSTALL_BROWSER=1 のときだけ、その場で取得してから処理を続行する。
111
113
  これは CI・コンテナ・繰り返し使う開発者が、往復を省くための抜け道になる。
112
114
 
113
115
  取得中も MCP の無音タイムアウトは進まない。progress ハートビートは createMcpServer が
114
116
  全ツール一律で送っており (src/mcp/server.ts)、ツール側で送出する必要はない。
115
117
  */
116
- export declare function ensureChromium(label: string, dependencies?: Readonly<ChromiumDependencies>, signal?: AbortSignal): Promise<ToolResult | undefined>;
118
+ export declare function ensureChromium(label: string, dependencies?: Readonly<ChromiumDependencies>, signal?: AbortSignal): Promise<FailedToolResult | undefined>;
117
119
  /**
118
120
  実行時依存 (@slidev/cli / dom-to-pptx / @slidev/parser 等) の取得状態を扱う依存。
119
121
  */
@@ -135,11 +137,11 @@ slide_create / slide_convert / slide_sync / slide_dev の 4 ツールが引数
135
137
  実行時解決、dev は @slidev/cli の bin を使う。そこで未取得のときの失敗の型を、1 か所に置いて揃える。
136
138
 
137
139
  プラグインとして導入した場合、実行時依存は同梱されているため、このガードは常に通る。
138
- 単体配布では起動層に重量依存を載せられないため、`setup` を呼ぶまで解決できない。
140
+ 単体配布では起動層に重量依存を載せられないため、`runtime_setup` を呼ぶまで解決できない。
139
141
  ensureChromium と違い、自動取得の抜け道は持たない。npm install は 600MB 級で、
140
- モデルから呼ばれるツールが無断で始めてよい規模ではないため、必ず `setup` を経由させる。
142
+ モデルから呼ばれるツールが無断で始めてよい規模ではないため、必ず `runtime_setup` を経由させる。
141
143
  */
142
- export declare function ensureRuntimeDependencies(label: string, dependencies?: Readonly<RuntimeDependencies>): ToolResult | undefined;
144
+ export declare function ensureRuntimeDependencies(label: string, dependencies?: Readonly<RuntimeDependencies>): FailedToolResult | undefined;
143
145
  export type NormalizedThemeArgument = {
144
146
  readonly ok: true;
145
147
  readonly theme: string;
@@ -1,16 +1,5 @@
1
- // 11 ツール共通の outputSchema と、ハンドラが系統別ファイルに複製していた定型処理。
2
- //
3
- // outputSchema は ToolResult (src/mcp/result.ts) と同形の zod object で、全ツールが共有する。
4
- // contract.test.ts は、required が artifacts・data・exitCode・message・ok の sorted であることを pin している。
5
- // stdout / stderr は任意として pin しているため、フィールドの必須性はここでのみ管理する。
6
- //
7
- // 出力捕捉・エラー整形・パス引数の説明文は、11 ツールで同一の振る舞いが要る。
8
- // とくに stdout / stderr は「捕捉したなら空でもキーを残す」が契約なので、実装はここに 1 本だけ置く。
9
- //
10
- // 引数の narrowing も、4 ファイル共通の方式に揃える。
11
- // SDK は inputSchema で検証済みの引数を渡してくる。ただしハンドラの引数型は Record<string, unknown> のまま。
12
- // そこで inputSchema と同じ z.object で parse し直して型を得る。
13
- // これは `as` キャスト禁止の下で型を得る手段で、検証済みの引数に対しては既定値の適用も冪等になる。
1
+ // 11 ツール共通の outputSchema・出力捕捉・エラー整形・実行時ガード。
2
+ // ハンドラは inputSchema と同じ z.object で引数を parse し直して型を得る (`as` を使わないため)。
14
3
  import path from 'node:path';
15
4
  import { z } from 'zod';
16
5
  import { areRuntimeDependenciesInstalled, DEPENDENCY_RECOVERY_HINT, runtimeDependencyRoot, } from '../../infra/_shared/dependency-root.js';
@@ -18,7 +7,8 @@ import { LOCK_CONFLICT_EXIT_CODE, LOCK_WAIT_SECONDS } from '../../infra/_shared/
18
7
  import { resolvePluginRoot } from '../../infra/_shared/plugin-root.js';
19
8
  import { installRuntimeDependencies, runtimeInstallStamp, RUNTIME_MANIFEST_DIRECTORY } from '../../infra/_shared/runtime-install.js';
20
9
  import { AUTO_INSTALL_ENV, browsersRoot, installChromium, isAutoInstallEnabled, isChromiumInstalled, } from '../../infra/playwright/chromium.js';
21
- import { createOutputCapture, truncateCapturedText } from '../result.js';
10
+ import { createOutputCapture, joinCapturedText, toCallToolResult } from '../result.js';
11
+ import { warningsOf } from '../warnings.js';
22
12
  import { toPosixPath } from '../windows-path.js';
23
13
  /**
24
14
  パス型パラメータの description 末尾に足す 1 文 (直前の文は句点で閉じてから連結する)。
@@ -30,21 +20,37 @@ import { toPosixPath } from '../windows-path.js';
30
20
  */
31
21
  export const WINDOWS_PATH_NOTE = String.raw `Windows-style paths (C:\... / \\wsl.localhost\<distro>\...) are accepted and `
32
22
  + 'converted to an absolute path under /mnt/<drive>/ or inside WSL.';
23
+ const WARNINGS_SCHEMA = z.array(z.string()).optional().describe('Warnings raised during the run (omitted when there are none). '
24
+ + 'Beyond 100 warnings or 64KB, the last item tells how many were omitted');
33
25
  /**
34
- ToolResult 同形の outputSchema。
35
-
36
- data はツールごとに形が異なる (対応 CLI の --json 出力と同形) ため、共通スキーマでは
37
- record として受け、同形性の検証は contract / parity テスト側で行う。
26
+ 全ツール共通の outputSchema。ツールごとの項目は形が違うため開いた object にし、共通の 4 項目だけ名前を持たせる。
38
27
  */
39
- export const TOOL_OUTPUT_SCHEMA = z.object({
40
- ok: z.boolean().describe('Whether the tool completed its intended run'),
41
- exitCode: z.number().describe('Exit code (0 = success)'),
42
- artifacts: z.array(z.string()).describe('Absolute paths of files and directories created or updated'),
43
- data: z.record(z.string(), z.unknown()).describe('Object with the details of the run'),
44
- message: z.string().describe('One-line summary for the calling agent'),
45
- stdout: z.string().optional().describe('Captured stdout (omitted when nothing was captured)'),
46
- stderr: z.string().optional().describe('Captured stderr (omitted when nothing was captured)'),
28
+ export const TOOL_OUTPUT_SCHEMA = z.looseObject({
29
+ kind: z.string().optional().describe('Failure kind (failure only)'),
30
+ detail: z.string().optional().describe('Full text of the failure and how to recover (failure only)'),
31
+ log: z.string().optional().describe('Raw output of the command or child process (failure only). Over 64KB, the end is kept and the first line notes the truncation'),
32
+ warnings: WARNINGS_SCHEMA,
47
33
  });
34
+ function stringArrayOf(value) {
35
+ return Array.isArray(value) ? value.filter((item) => typeof item === 'string') : [];
36
+ }
37
+ /**
38
+ 捕捉した出力を ToolResult の data へ移す。warning の文は warnings へ (既にある文と重ねて重複を除く)、
39
+ 失敗のときは出力の全体を log へ入れる。
40
+ */
41
+ export function withCapturedOutput(result, captured) {
42
+ const existing = stringArrayOf(result.data['warnings']);
43
+ const warnings = [...new Set([...existing, ...(captured.warnings ?? warningsOf(captured.stderr))])];
44
+ const log = result.ok ? '' : joinCapturedText([captured.stdout, captured.stderr]);
45
+ return {
46
+ ...result,
47
+ data: {
48
+ ...result.data,
49
+ ...((warnings.length > 0 || 'warnings' in result.data) && { warnings }),
50
+ ...(log !== '' && { log }),
51
+ },
52
+ };
53
+ }
48
54
  /**
49
55
  MCP サーバの process.stdout は JSON-RPC 専有なので、コマンドの出力は必ずここへ逃がす。
50
56
  */
@@ -54,35 +60,38 @@ export function captureCommandOutput() {
54
60
  return {
55
61
  stdout: stdout.stream,
56
62
  stderr: stderr.stream,
57
- part: () => ({ stdout: stdout.text(), stderr: stderr.text() }),
63
+ finish: result => toCallToolResult(withCapturedOutput(result, { stdout: stdout.text(), stderr: stderr.text(), warnings: stderr.warnings() })),
64
+ warnings: () => stderr.warnings(),
58
65
  };
59
66
  }
60
67
  /**
61
- 子プロセスの結果を ToolResult の stdout / stderr へ載せる形に整える。
62
-
63
- Writable を通さない出力にも、captureCommandOutput と同じ上限をかけるための関数。
64
- 空でもキーを残すのは CommandOutput.part() と同じ契約。
68
+ 子プロセスの出力を result の data へ移す。warning は切り詰める前の stderr の全体から取る。
65
69
  */
66
- export function spawnOutputPart(result) {
67
- return {
68
- stdout: truncateCapturedText(result.stdout),
69
- stderr: truncateCapturedText(result.stderr),
70
- };
70
+ export function withSpawnOutput(result, spawned) {
71
+ return withCapturedOutput(result, { stdout: spawned.stdout, stderr: spawned.stderr });
71
72
  }
72
73
  /**
73
- ツールの失敗 message / data.detail に載せる 1 行の理由。
74
+ ツールの失敗の detail に載せる 1 行の理由。
74
75
  */
75
76
  export function formatError(error) {
76
77
  /* c8 ignore next -- 非 Error 例外は本実装範囲では未発生、false 分岐は防御網のみ */
77
78
  return error instanceof Error ? error.message : String(error);
78
79
  }
79
80
  /**
80
- 文面の違反で生成を止めたときの message。drawio_create と evidence_create で同じ文言にする。
81
+ 文面の違反で生成を止めたときの直し方。drawio_create と evidence_create で同じ文言にする。
81
82
  */
82
83
  export function textViolationMessage(count) {
83
84
  return `${count.toString()} text violations; fix the text without loosening the rules, then run again`;
84
85
  }
85
86
  /**
87
+ 失敗の detail。文面の違反なら、違反の一覧に直し方の 1 行を足す。
88
+ */
89
+ export function failureDetailOf(error, data) {
90
+ const violationCount = violationCountOf(data);
91
+ const detail = formatError(error);
92
+ return violationCount === undefined ? detail : `${detail}\n${textViolationMessage(violationCount)}`;
93
+ }
94
+ /**
86
95
  errorData の data から、文面の違反の件数を取る。違反を持たない失敗は undefined。
87
96
  */
88
97
  export function violationCountOf(data) {
@@ -90,14 +99,6 @@ export function violationCountOf(data) {
90
99
  return Array.isArray(violations) ? violations.length : undefined;
91
100
  }
92
101
  /**
93
- chromium 不在 / 取得失敗で実処理を諦めたときの exit code (各コマンドの RuntimeError と同じ 1)。
94
- */
95
- export const CHROMIUM_UNAVAILABLE_EXIT_CODE = 1;
96
- /**
97
- 実行時依存 (永続層) 不在 / 取得失敗で実処理を諦めたときの exit code。
98
- */
99
- export const RUNTIME_UNAVAILABLE_EXIT_CODE = 1;
100
- /**
101
102
  永続層の場所を特定できないときに利用者向けの応答へ載せる既定の表記。
102
103
  */
103
104
  export const RUNTIME_ROOT_PLACEHOLDER = '<data-dir>/mcp-dist';
@@ -178,7 +179,7 @@ function chromiumFailureReason(result) {
178
179
  return `download timed out${NETWORK_HINT}`;
179
180
  if (result.exitCode === null) {
180
181
  return result.signal === null
181
- ? 'could not start the download command (see stderr for the reason); rebuild node_modules (pnpm install), then run again'
182
+ ? 'could not start the download command (see log for the reason); rebuild node_modules (pnpm install), then run again'
182
183
  : `download command was interrupted by ${result.signal}; the download was cut off externally`;
183
184
  }
184
185
  return `download command exited with ${String(result.exitCode)}${NETWORK_HINT}`;
@@ -189,7 +190,7 @@ chromium を要するツールのハンドラ冒頭で使う実行時ガード (
189
190
 
190
191
  `pecotv mcp` は接続タイムアウト (Claude Code の MCP_TIMEOUT は 30000ms が初期値) に収めるため、
191
192
  起動時に chromium を取得しない。モデルから呼ばれるツールが 120MB のダウンロードを無断で始めないよう、
192
- 初期状態では取得せず、`setup` ツールの呼び出しを案内する。
193
+ 初期状態では取得せず、`runtime_setup` ツールの呼び出しを案内する。
193
194
  PECOTV_AUTO_INSTALL_BROWSER=1 のときだけ、その場で取得してから処理を続行する。
194
195
  これは CI・コンテナ・繰り返し使う開発者が、往復を省くための抜け道になる。
195
196
 
@@ -204,17 +205,14 @@ signal) {
204
205
  if (!dependencies.isAutoInstallEnabled()) {
205
206
  return {
206
207
  ok: false,
207
- exitCode: CHROMIUM_UNAVAILABLE_EXIT_CODE,
208
- artifacts: [],
208
+ kind: 'chromium-not-installed',
209
+ detail: `cannot run ${label}: Playwright Chromium is not installed in ${expectedLocation(dependencies)}`
210
+ + '; call the `runtime_setup` tool to download it (about 120MB)'
211
+ + `; to automate the download, set ${AUTO_INSTALL_ENV}=1`,
209
212
  data: {
210
213
  event: 'chromium.unavailable',
211
- reason: 'chromium-not-installed',
212
- detail: `${label} needs Playwright Chromium, but it is not found in ${expectedLocation(dependencies)}`
213
- + '; call the `setup` tool to download it (about 120MB)'
214
- + `; to automate the download, set ${AUTO_INSTALL_ENV}=1`,
215
214
  expectedAt: expectedLocation(dependencies),
216
215
  },
217
- message: `cannot run ${label}: Playwright Chromium is not installed; call the \`setup\` tool`,
218
216
  };
219
217
  }
220
218
  const result = await dependencies.install(signal);
@@ -225,20 +223,16 @@ signal) {
225
223
  const detail = result.exitCode === 0
226
224
  ? `download command succeeded, but chromium is not in ${expectedLocation(dependencies)}`
227
225
  : chromiumInstallFailureDetail(result);
228
- return {
226
+ // playwright install は失敗原因を stdout に書くこともあるため、両方を log に入れる。
227
+ return withSpawnOutput({
229
228
  ok: false,
230
- exitCode: CHROMIUM_UNAVAILABLE_EXIT_CODE,
231
- artifacts: [],
229
+ kind: 'chromium-install-failed',
230
+ detail: `cannot run ${label}: downloading chromium with ${AUTO_INSTALL_ENV}=1 failed: ${detail}`,
232
231
  data: {
233
232
  event: 'chromium.unavailable',
234
- reason: 'chromium-install-failed',
235
- detail: `downloading chromium with ${AUTO_INSTALL_ENV}=1 for ${label} failed: ${detail}`,
236
233
  expectedAt: expectedLocation(dependencies),
237
234
  },
238
- message: `cannot run ${label}: Playwright Chromium download failed`,
239
- // 失敗原因が stdout 側にあることもある (playwright install は進捗・取得先を stdout へ書く)。
240
- ...spawnOutputPart(result),
241
- };
235
+ }, result);
242
236
  }
243
237
  export function runtimeDefaultDependencies() {
244
238
  const manifestPath = path.join(resolvePluginRoot(), RUNTIME_MANIFEST_DIRECTORY, 'package.json');
@@ -269,9 +263,9 @@ slide_create / slide_convert / slide_sync / slide_dev の 4 ツールが引数
269
263
  実行時解決、dev は @slidev/cli の bin を使う。そこで未取得のときの失敗の型を、1 か所に置いて揃える。
270
264
 
271
265
  プラグインとして導入した場合、実行時依存は同梱されているため、このガードは常に通る。
272
- 単体配布では起動層に重量依存を載せられないため、`setup` を呼ぶまで解決できない。
266
+ 単体配布では起動層に重量依存を載せられないため、`runtime_setup` を呼ぶまで解決できない。
273
267
  ensureChromium と違い、自動取得の抜け道は持たない。npm install は 600MB 級で、
274
- モデルから呼ばれるツールが無断で始めてよい規模ではないため、必ず `setup` を経由させる。
268
+ モデルから呼ばれるツールが無断で始めてよい規模ではないため、必ず `runtime_setup` を経由させる。
275
269
  */
276
270
  export function ensureRuntimeDependencies(label, dependencies = runtimeDefaultDependencies()) {
277
271
  if (dependencies.isInstalled())
@@ -279,16 +273,13 @@ export function ensureRuntimeDependencies(label, dependencies = runtimeDefaultDe
279
273
  const expectedAt = dependencies.root() ?? RUNTIME_ROOT_PLACEHOLDER;
280
274
  return {
281
275
  ok: false,
282
- exitCode: RUNTIME_UNAVAILABLE_EXIT_CODE,
283
- artifacts: [],
276
+ kind: 'runtime-dependencies-not-installed',
277
+ detail: `cannot run ${label}: runtime dependencies are not installed`
278
+ + ` (@slidev/cli / dom-to-pptx / @slidev/parser cannot be resolved); ${DEPENDENCY_RECOVERY_HINT}`,
284
279
  data: {
285
280
  event: 'runtime-dependencies.unavailable',
286
- reason: 'runtime-dependencies-not-installed',
287
- detail: `${label} needs @slidev/cli / dom-to-pptx / @slidev/parser, which cannot be resolved; `
288
- + DEPENDENCY_RECOVERY_HINT,
289
281
  expectedAt,
290
282
  },
291
- message: `cannot run ${label}: runtime dependencies are not installed; call the \`setup\` tool`,
292
283
  };
293
284
  }
294
285
  /**
@@ -7,17 +7,18 @@
7
7
  // deps はハンドラ内で毎回組み立てる。既定 deps ファクトリは CLAUDE_PLUGIN_ROOT 未設定で throw する。
8
8
  // module top-level で評価すると、サーバ起動と tools/list がまとめて落ちる。
9
9
  import { z } from 'zod';
10
- import { assertOutputExtension as assertDrawioExportOutputExtension, drawioExportDefaultDependencies, errorToReason as drawioExportErrorToReason, executeDrawioExport, toExitCode as drawioExportToExitCode, } from '../../commands/drawio/export.js';
11
- import { drawioUrlDefaultDependencies, errorData as drawioUrlErrorData, executeDrawioUrl, toExitCode as drawioUrlToExitCode, } from '../../commands/drawio/url.js';
10
+ import { assertOutputExtension as assertDrawioExportOutputExtension, drawioExportDefaultDependencies, errorToReason as drawioExportErrorToReason, executeDrawioExport, } from '../../commands/drawio/export.js';
11
+ import { drawioUrlDefaultDependencies, errorData as drawioUrlErrorData, errorToReason as drawioUrlErrorToReason, executeDrawioUrl, } from '../../commands/drawio/url.js';
12
12
  import { createDiagnostics } from '../../diagnostics.js';
13
+ import { failureKindOf } from '../../domain/_shared/failure-kind.js';
13
14
  import { resolvePluginRoot } from '../../infra/_shared/plugin-root.js';
14
15
  import { defaultIconRoot } from '../../infra/drawio/icons.js';
15
- import { parsePathArguments, toCallToolResult } from '../result.js';
16
- import { captureCommandOutput, chromiumDefaultDependencies, ensureChromium, formatError, textViolationMessage, violationCountOf, normalizeThemeArgument, TOOL_OUTPUT_SCHEMA, WINDOWS_PATH_NOTE, } from './_shared.js';
16
+ import { parsePathArguments, toCallToolResult, withoutCommonFailureFields } from '../result.js';
17
+ import { captureCommandOutput, chromiumDefaultDependencies, ensureChromium, failureDetailOf, formatError, normalizeThemeArgument, TOOL_OUTPUT_SCHEMA, WINDOWS_PATH_NOTE, } from './_shared.js';
17
18
  const drawioCreateInput = z.object({
18
19
  input_path: z.string().describe('Absolute path of the input .drawio file. ' + WINDOWS_PATH_NOTE),
19
20
  mode: z.enum(['view', 'edit']).describe('Purpose of the generated URL (view / edit). The generated URL is the same for both').default('view'),
20
- out_path: z.string().describe('Absolute path of the .html file to write the viewer HTML to (opening it redirects to draw.io). If omitted, only the URL is returned in data.url. ' + WINDOWS_PATH_NOTE).optional(),
21
+ out_path: z.string().describe('Absolute path of the .html file to write the viewer HTML to (opening it redirects to draw.io). If omitted, only the URL is returned in url. ' + WINDOWS_PATH_NOTE).optional(),
21
22
  theme: z.string()
22
23
  .describe('Theme used to check the font and font size: `git+https://<host>/<owner>/<repo>.git#<tag>`, `file:<absolute path>`, '
23
24
  + 'or the absolute path of a talk-dir or a theme root. If omitted, the theme of the talk-dir is used when the diagram is under its `public/`; '
@@ -34,14 +35,17 @@ const drawioExportInput = z.object({
34
35
  pdf: z.boolean().describe('Whether to also write a PDF as a sibling file (<out_path with the extension replaced by .pdf>) alongside the SVG').default(true),
35
36
  });
36
37
  /**
37
- PNG を出せなかったときの exit code。CLI の「警告あり」と同じ 3 に揃える。
38
- */
39
- const PNG_SKIPPED_EXIT_CODE = 3;
40
- /**
41
38
  message 末尾の警告件数サフィックス。drawio_create / drawio_export で表記を揃える。
42
39
  */
43
40
  function warningSuffix(warningCount) {
44
- return warningCount > 0 ? ` (${String(warningCount)} warnings; details in stderr)` : '';
41
+ return warningCount > 0 ? ` (${String(warningCount)} warnings; see warnings)` : '';
42
+ }
43
+ /**
44
+ CLI の `--json` の `warnings` は件数。MCP では warnings を捕捉した文の配列にするため、件数を外す (件数は配列の長さで分かる)。
45
+ */
46
+ function withoutWarningCount(data) {
47
+ const { warnings: _count, ...rest } = data;
48
+ return rest;
45
49
  }
46
50
  function drawioCreateMessage(outputFile, warningCount) {
47
51
  const warnings = warningSuffix(warningCount);
@@ -53,22 +57,20 @@ function drawioCreateMessage(outputFile, warningCount) {
53
57
  chromium 不在で PNG を諦めたときの結果を、CLI の degrade と同形に寄せる (SC-002)。
54
58
 
55
59
  CLI (`pecotv drawio url`) は PNG 生成の失敗を warning に格下げする。
56
- 表示用 HTML は書いたうえで、`png: null` / `pngFailed: true` / warnings +1 / exit 3 を返す。
60
+ 表示用 HTML は書いたうえで、`png: null` / `pngFailed: true` / warning 1 件を返す。
57
61
  MCP だけが実処理の前に hard-fail すると、CLI と結果が食い違う。
58
62
  degrade できる条件はこれだけ。drawio_export と slide_convert は、chromium が無いと成果物を 1 つも作れない。
59
- data は CLI の PNG 失敗時と同一にし、`setup` の誘導は message へ載せる。
63
+ 項目は CLI の PNG 失敗時と同一にし、`runtime_setup` の誘導は message へ載せる。
60
64
  */
61
- function degradeToPngSkipped(execution, unavailable) {
65
+ function degradeToPngSkipped(execution, unavailable, warningCount) {
62
66
  return {
63
- exitCode: PNG_SKIPPED_EXIT_CODE,
64
67
  data: {
65
- ...execution.data,
68
+ ...withoutWarningCount(execution.data),
66
69
  // eslint-disable-next-line unicorn/no-null -- PNG 失敗時に png: null を返すことが CLI との契約
67
70
  png: null,
68
71
  pngFailed: true,
69
- warnings: execution.warningCount + 1,
70
72
  },
71
- message: `${drawioCreateMessage(execution.outputFile, execution.warningCount + 1)}: ${unavailable.message}`,
73
+ message: `${drawioCreateMessage(execution.outputFile, warningCount)}: ${unavailable.detail}`,
72
74
  };
73
75
  }
74
76
  const handleDrawioCreate = async (arguments_,
@@ -84,10 +86,9 @@ call) => {
84
86
  const detail = normalized.detail;
85
87
  return toCallToolResult({
86
88
  ok: false,
87
- exitCode: 2,
88
- artifacts: [],
89
- data: { event: 'drawio.url.error', reason: 'invalid-option', detail },
90
- message: `pecotv drawio url: ${detail}`,
89
+ kind: 'invalid-option',
90
+ detail: `pecotv drawio url: ${detail}`,
91
+ data: { event: 'drawio.url.error' },
91
92
  });
92
93
  }
93
94
  // PNG を書くときだけ chromium が要る。out_path 省略時と png: false は URL 生成だけで完結する。
@@ -95,38 +96,29 @@ call) => {
95
96
  ? await ensureChromium('drawio_create PNG output', chromiumDefaultDependencies(), call.signal)
96
97
  : undefined;
97
98
  const output = captureCommandOutput();
98
- // CLI は capturePng の失敗を stderr へ書いてから warning に数える。
99
- // 同じ行を残して、「警告 N 件、詳細は stderr」という message を CLI と MCP で同じ意味にする。
99
+ // CLI と同じく PNG の失敗を warning の行に書き、warnings に入れる。
100
100
  if (unavailable !== undefined)
101
- createDiagnostics(output.stderr).warning(`PNG export failed: ${unavailable.message}`);
101
+ createDiagnostics(output.stderr).warning(`PNG export failed: ${unavailable.detail}`);
102
102
  try {
103
103
  const execution = await executeDrawioUrl(input.input_path,
104
104
  // chromium が無いときは PNG を要求せずに実行する (表示用 HTML の生成は成立する)。
105
105
  { mode: input.mode, png: input.png && unavailable === undefined, theme: normalized?.theme, output: input.out_path }, { ...drawioUrlDefaultDependencies(), stdout: output.stdout, stderr: output.stderr, signal: call.signal });
106
- // 警告あり (exitCode 3) でも URL の生成そのものは完了しているので ok: true。
107
- const result = {
106
+ // 警告あり (CLI の exit 3) でも URL の生成そのものは完了しているので成功で返す。file・png の項目が CLI の artifacts と同じパスを持つ。
107
+ return output.finish({
108
108
  ok: true,
109
- exitCode: execution.exitCode,
110
- artifacts: execution.artifacts,
111
- data: execution.data,
112
- message: drawioCreateMessage(execution.outputFile, execution.warningCount),
113
- ...(unavailable !== undefined && degradeToPngSkipped(execution, unavailable)),
114
- ...output.part(),
115
- };
116
- return toCallToolResult(result);
109
+ data: withoutWarningCount(execution.data),
110
+ message: drawioCreateMessage(execution.outputFile, output.warnings().length),
111
+ ...(unavailable !== undefined && degradeToPngSkipped(execution, unavailable, output.warnings().length)),
112
+ });
117
113
  }
118
114
  catch (error) {
119
115
  const data = drawioUrlErrorData(error);
120
- const violationCount = violationCountOf(data);
121
- const result = {
116
+ return output.finish({
122
117
  ok: false,
123
- exitCode: drawioUrlToExitCode(error),
124
- artifacts: [],
125
- data,
126
- message: violationCount === undefined ? `pecotv drawio url: ${formatError(error)}` : textViolationMessage(violationCount),
127
- ...output.part(),
128
- };
129
- return toCallToolResult(result);
118
+ kind: failureKindOf(drawioUrlErrorToReason(error)),
119
+ detail: `pecotv drawio url: ${failureDetailOf(error, data)}`,
120
+ data: withoutCommonFailureFields(data),
121
+ });
130
122
  }
131
123
  };
132
124
  const handleDrawioExport = async (arguments_,
@@ -156,39 +148,33 @@ call) => {
156
148
  const output = captureCommandOutput();
157
149
  try {
158
150
  const execution = await executeDrawioExport(input.input_path, { icons: iconsRoot, output: input.out_path, printHash: input.print_hash, pdf: input.pdf }, { ...drawioExportDefaultDependencies(), stdout: output.stdout, stderr: output.stderr });
159
- // 警告あり (exitCode 3。PDF 生成失敗) でも SVG の書き出しは完了しているので ok: true。
160
- const result = {
151
+ // 警告あり (CLI の exit 3。PDF 生成失敗) でも SVG の書き出しは完了しているので成功で返す。file・pdf の項目が CLI の artifacts と同じパスを持つ。
152
+ return output.finish({
161
153
  ok: true,
162
- exitCode: execution.exitCode,
163
- artifacts: execution.artifacts,
164
- data: execution.data,
165
- message: drawioExportMessage(execution),
166
- ...output.part(),
167
- };
168
- return toCallToolResult(result);
154
+ data: withoutWarningCount(execution.data),
155
+ message: drawioExportMessage(execution, output.warnings().length),
156
+ });
169
157
  }
170
158
  catch (error) {
171
- return toCallToolResult({ ...drawioExportFailure(error), ...output.part() });
159
+ return output.finish(drawioExportFailure(error));
172
160
  }
173
161
  };
174
162
  /**
175
163
  drawio_export の失敗を CLI の `--json` エラーと同形の ToolResult に写す。
176
164
  */
177
165
  function drawioExportFailure(error) {
178
- const detail = formatError(error);
179
166
  return {
180
167
  ok: false,
181
- exitCode: drawioExportToExitCode(error),
182
- artifacts: [],
183
- data: { event: 'drawio.export.error', reason: drawioExportErrorToReason(error), detail },
184
- message: `pecotv drawio export: ${detail}`,
168
+ kind: failureKindOf(drawioExportErrorToReason(error)),
169
+ detail: `pecotv drawio export: ${formatError(error)}`,
170
+ data: { event: 'drawio.export.error' },
185
171
  };
186
172
  }
187
- function drawioExportMessage(execution) {
173
+ function drawioExportMessage(execution, warningCount) {
188
174
  if (execution.outputFile === undefined)
189
175
  return `computed composite hash: ${execution.sourceSha256}`;
190
176
  const pdf = execution.pdfFile === undefined ? '' : ` (PDF: ${execution.pdfFile})`;
191
- return `wrote SVG to ${execution.outputFile}${pdf}${warningSuffix(execution.warningCount)}`;
177
+ return `wrote SVG to ${execution.outputFile}${pdf}${warningSuffix(warningCount)}`;
192
178
  }
193
179
  // annotations は SDK 既定 (readOnlyHint: false / openWorldHint: true) と一致するため付けない。
194
180
  // どちらのツールもファイルを書き、PNG 生成では viewer.diagrams.net、SVG 生成では embed.diagrams.net へ到達する。
@@ -196,7 +182,7 @@ export const drawioCreateTool = {
196
182
  name: 'drawio_create',
197
183
  config: {
198
184
  title: 'Output a drawio diagram as a deliverable',
199
- description: 'Turns drawio XML into a deliverable that opens directly in a browser. Writes viewer HTML (.html; opening it redirects to draw.io) to out_path and, by default, also writes a rendered PNG (useful for checking the rendering). icon:// references are resolved to data URIs and embedded. Before generating, it checks the diagram labels against the text rules and generates nothing if there is a violation. The font and font size are checked against the theme declaration (theme, or the theme of the talk-dir that is an ancestor of the diagram), and the result is returned in data.theme.',
185
+ description: 'Turns drawio XML into a deliverable that opens directly in a browser. Writes viewer HTML (.html; opening it redirects to draw.io) to out_path and, by default, also writes a rendered PNG (useful for checking the rendering). icon:// references are resolved to data URIs and embedded. Before generating, it checks the diagram labels against the text rules and generates nothing if there is a violation. The font and font size are checked against the theme declaration (theme, or the theme of the talk-dir that is an ancestor of the diagram), and the result is returned in theme.',
200
186
  inputSchema: drawioCreateInput,
201
187
  outputSchema: TOOL_OUTPUT_SCHEMA,
202
188
  },
@@ -1,12 +1,12 @@
1
1
  // evidence 系の MCP ツール定義 (evidence_create)。
2
2
  //
3
- // ハンドラは既存 CLI と同じ executeEvidenceCreate を呼ぶ。CLI の `--json` が出す
4
- // オブジェクトをそのまま ToolResult.data に載せるため、CLI と MCP の結果は同形になる。
3
+ // ハンドラは既存 CLI と同じ executeEvidenceCreate を呼び、CLI の `--json` が出すオブジェクトをそのまま項目として返す。
5
4
  import path from 'node:path';
6
5
  import { z } from 'zod';
7
- import { errorData, EVIDENCE_CREATE_FAILURE_EXIT_CODE, evidenceCreateDefaultDependencies, executeEvidenceCreate, } from '../../commands/evidence-xlsx/create.js';
8
- import { parsePathArguments, toCallToolResult } from '../result.js';
9
- import { captureCommandOutput, formatError, textViolationMessage, TOOL_OUTPUT_SCHEMA, violationCountOf, WINDOWS_PATH_NOTE } from './_shared.js';
6
+ import { errorData, errorToReason, evidenceCreateDefaultDependencies, executeEvidenceCreate, } from '../../commands/evidence-xlsx/create.js';
7
+ import { failureKindOf } from '../../domain/_shared/failure-kind.js';
8
+ import { parsePathArguments, toCallToolResult, withoutCommonFailureFields } from '../result.js';
9
+ import { captureCommandOutput, failureDetailOf, TOOL_OUTPUT_SCHEMA, WINDOWS_PATH_NOTE } from './_shared.js';
10
10
  const evidenceCreateInput = z.object({
11
11
  input_path: z.string().describe('Absolute path of the EvidenceSpec JSON. ' + WINDOWS_PATH_NOTE),
12
12
  out_path: z.string().optional().describe('Absolute path of the xlsx to write. If omitted, evidence.xlsx in the same directory as input_path. ' + WINDOWS_PATH_NOTE),
@@ -36,27 +36,20 @@ async function handleEvidenceCreate(arguments_) {
36
36
  };
37
37
  const data = await executeEvidenceCreate({ input: input.input_path, out: input.out_path ?? defaultOutPath(input.input_path) }, dependencies);
38
38
  const counts = `${String(data.items)} items; ${String(data.annotations)} annotations; ${String(data.skipped.length)} skipped`;
39
- return toCallToolResult({
39
+ // 書いた xlsx のパスは outPath の項目で返す。
40
+ return output.finish({
40
41
  ok: true,
41
- exitCode: 0,
42
- artifacts: [data.outPath],
43
42
  data: { ...data },
44
43
  message: `generated evidence xlsx: ${data.outPath} (${counts})`,
45
- ...output.part(),
46
44
  });
47
45
  }
48
46
  catch (error) {
49
47
  const data = errorData(error);
50
- const violationCount = violationCountOf(data);
51
- return toCallToolResult({
48
+ return output.finish({
52
49
  ok: false,
53
- // usage エラー (exit 2) は commander の引数検証にしか無い。MCP では
54
- // inputSchema と parsePathArguments が先に弾くため、ここは実行失敗の 1 のみ。
55
- exitCode: EVIDENCE_CREATE_FAILURE_EXIT_CODE,
56
- artifacts: [],
57
- data,
58
- message: violationCount === undefined ? formatError(error) : textViolationMessage(violationCount),
59
- ...output.part(),
50
+ kind: failureKindOf(errorToReason(error)),
51
+ detail: failureDetailOf(error, data),
52
+ data: withoutCommonFailureFields(data),
60
53
  });
61
54
  }
62
55
  }