inkbone 0.0.0-stage → 2.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.
- package/LICENSE +21 -0
- package/README.en.md +318 -0
- package/README.md +333 -2
- package/bin/inkbone.mjs +941 -0
- package/configs/genres.json +570 -0
- package/configs/messages.json +302 -0
- package/configs/platforms.json +62 -0
- package/configs/presets.json +265 -0
- package/configs/severity.json +52 -0
- package/configs/zh-linguistics.json +986 -0
- package/configs/zh-traditional.json +97 -0
- package/examples/claude-code-hooks.json +15 -0
- package/examples/mcp-config.json +12 -0
- package/package.json +61 -4
- package/prompts/00-style-architect.md +42 -0
- package/prompts/01-beat-planner.md +54 -0
- package/prompts/02-paratactic-renderer.md +60 -0
- package/prompts/03-targeted-rewriter.md +39 -0
- package/prompts/04-evidence-reviewer.md +39 -0
- package/prompts/05-reader-simulator.md +54 -0
- package/prompts/06-ledger-importer.md +41 -0
- package/prompts/07-chapter-settler.md +66 -0
- package/resources/bad_vs_good_cases.md +98 -0
- package/resources/eval/blind-read-instructions.md +18 -0
- package/resources/genre_playbooks/classical-xianxia.md +22 -0
- package/resources/genre_playbooks/general-clean.md +19 -0
- package/resources/genre_playbooks/historical-court.md +21 -0
- package/resources/genre_playbooks/light-fantasy.md +21 -0
- package/resources/genre_playbooks/mystery-thriller.md +22 -0
- package/resources/genre_playbooks/romance-emotional.md +20 -0
- package/resources/genre_playbooks/scifi-wasteland.md +21 -0
- package/resources/genre_playbooks/urban-realism.md +22 -0
- package/resources/genre_playbooks/wuxia-jianghu.md +21 -0
- package/resources/micro_techniques.md +77 -0
- package/skills/inkbone/LICENSE +21 -0
- package/skills/inkbone/README.md +334 -0
- package/skills/inkbone/SKILL.md +155 -0
- package/skills/inkbone/benchmarks/eval-set/README.md +49 -0
- package/skills/inkbone/benchmarks/eval-set/public-pairs.json +42 -0
- package/skills/inkbone/benchmarks/eval-set/seeds.json +42 -0
- package/skills/inkbone/bin/inkbone.mjs +941 -0
- package/skills/inkbone/configs/genres.json +570 -0
- package/skills/inkbone/configs/messages.json +302 -0
- package/skills/inkbone/configs/platforms.json +62 -0
- package/skills/inkbone/configs/presets.json +265 -0
- package/skills/inkbone/configs/severity.json +52 -0
- package/skills/inkbone/configs/zh-linguistics.json +986 -0
- package/skills/inkbone/configs/zh-traditional.json +97 -0
- package/skills/inkbone/package.json +63 -0
- package/skills/inkbone/prompts/00-style-architect.md +42 -0
- package/skills/inkbone/prompts/01-beat-planner.md +54 -0
- package/skills/inkbone/prompts/02-paratactic-renderer.md +60 -0
- package/skills/inkbone/prompts/03-targeted-rewriter.md +39 -0
- package/skills/inkbone/prompts/04-evidence-reviewer.md +39 -0
- package/skills/inkbone/prompts/05-reader-simulator.md +54 -0
- package/skills/inkbone/prompts/06-ledger-importer.md +41 -0
- package/skills/inkbone/prompts/07-chapter-settler.md +66 -0
- package/skills/inkbone/resources/bad_vs_good_cases.md +98 -0
- package/skills/inkbone/resources/eval/blind-read-instructions.md +18 -0
- package/skills/inkbone/resources/genre_playbooks/classical-xianxia.md +22 -0
- package/skills/inkbone/resources/genre_playbooks/general-clean.md +19 -0
- package/skills/inkbone/resources/genre_playbooks/historical-court.md +21 -0
- package/skills/inkbone/resources/genre_playbooks/light-fantasy.md +21 -0
- package/skills/inkbone/resources/genre_playbooks/mystery-thriller.md +22 -0
- package/skills/inkbone/resources/genre_playbooks/romance-emotional.md +20 -0
- package/skills/inkbone/resources/genre_playbooks/scifi-wasteland.md +21 -0
- package/skills/inkbone/resources/genre_playbooks/urban-realism.md +22 -0
- package/skills/inkbone/resources/genre_playbooks/wuxia-jianghu.md +21 -0
- package/skills/inkbone/resources/micro_techniques.md +77 -0
- package/skills/inkbone/src/auditor.mjs +24 -0
- package/skills/inkbone/src/benchmark-runner.mjs +71 -0
- package/skills/inkbone/src/boundary-compiler.mjs +54 -0
- package/skills/inkbone/src/browser-doctor.mjs +30 -0
- package/skills/inkbone/src/calibrator.mjs +175 -0
- package/skills/inkbone/src/config-loader.mjs +233 -0
- package/skills/inkbone/src/continuity.mjs +5 -0
- package/skills/inkbone/src/core/auditor.mjs +914 -0
- package/skills/inkbone/src/core/boundary-compiler.mjs +423 -0
- package/skills/inkbone/src/core/browser-doctor.mjs +318 -0
- package/skills/inkbone/src/core/config-compiler.mjs +434 -0
- package/skills/inkbone/src/core/continuity.mjs +158 -0
- package/skills/inkbone/src/core/evidence-validator.mjs +77 -0
- package/skills/inkbone/src/core/exporter.mjs +128 -0
- package/skills/inkbone/src/core/formatter.mjs +241 -0
- package/skills/inkbone/src/core/ledger-manager.mjs +576 -0
- package/skills/inkbone/src/core/normalizer.mjs +517 -0
- package/skills/inkbone/src/core/profiler.mjs +686 -0
- package/skills/inkbone/src/core/rule-engine.mjs +1536 -0
- package/skills/inkbone/src/core/style-profiler.mjs +229 -0
- package/skills/inkbone/src/detector.mjs +270 -0
- package/skills/inkbone/src/doctor.mjs +428 -0
- package/skills/inkbone/src/evaluation.mjs +311 -0
- package/skills/inkbone/src/evidence-validator.mjs +15 -0
- package/skills/inkbone/src/exporter.mjs +106 -0
- package/skills/inkbone/src/formatter.mjs +34 -0
- package/skills/inkbone/src/importer.mjs +230 -0
- package/skills/inkbone/src/index.mjs +116 -0
- package/skills/inkbone/src/ledger-manager.mjs +15 -0
- package/skills/inkbone/src/mcp-server.mjs +861 -0
- package/skills/inkbone/src/normalizer.mjs +73 -0
- package/skills/inkbone/src/profiler.mjs +17 -0
- package/skills/inkbone/src/rule-engine.mjs +73 -0
- package/skills/inkbone/src/rule-stats.mjs +142 -0
- package/skills/inkbone/src/style-profiler.mjs +25 -0
- package/src/auditor.mjs +24 -0
- package/src/benchmark-runner.mjs +71 -0
- package/src/boundary-compiler.mjs +54 -0
- package/src/browser-doctor.mjs +30 -0
- package/src/calibrator.mjs +175 -0
- package/src/config-loader.mjs +233 -0
- package/src/continuity.mjs +5 -0
- package/src/core/auditor.mjs +914 -0
- package/src/core/boundary-compiler.mjs +423 -0
- package/src/core/browser-doctor.mjs +318 -0
- package/src/core/config-compiler.mjs +434 -0
- package/src/core/continuity.mjs +158 -0
- package/src/core/evidence-validator.mjs +77 -0
- package/src/core/exporter.mjs +128 -0
- package/src/core/formatter.mjs +241 -0
- package/src/core/ledger-manager.mjs +576 -0
- package/src/core/normalizer.mjs +517 -0
- package/src/core/profiler.mjs +686 -0
- package/src/core/rule-engine.mjs +1536 -0
- package/src/core/style-profiler.mjs +229 -0
- package/src/detector.mjs +270 -0
- package/src/doctor.mjs +428 -0
- package/src/evaluation.mjs +311 -0
- package/src/evidence-validator.mjs +15 -0
- package/src/exporter.mjs +106 -0
- package/src/formatter.mjs +34 -0
- package/src/importer.mjs +230 -0
- package/src/index.mjs +116 -0
- package/src/ledger-manager.mjs +15 -0
- package/src/mcp-server.mjs +861 -0
- package/src/normalizer.mjs +73 -0
- package/src/profiler.mjs +17 -0
- package/src/rule-engine.mjs +73 -0
- package/src/rule-stats.mjs +142 -0
- package/src/style-profiler.mjs +25 -0
|
@@ -0,0 +1,861 @@
|
|
|
1
|
+
// 零第三方依赖 MCP Server(JSON-RPC 2.0 over stdio),完整实现 Tools(9) + Prompts(8) + Resources(11) 三件套
|
|
2
|
+
// 自动兼容 NDJSON 与 Content-Length 两种帧协议
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { findProjectConfig, loadProjectConfig } from "./config-loader.mjs";
|
|
7
|
+
import { auditChapterText } from "./auditor.mjs";
|
|
8
|
+
import { compileBoundaryPacket } from "./boundary-compiler.mjs";
|
|
9
|
+
import { diagnoseProject } from "./doctor.mjs";
|
|
10
|
+
import { normalizeProseText, normalizeFiles } from "./normalizer.mjs";
|
|
11
|
+
import { validateEvidenceReview } from "./evidence-validator.mjs";
|
|
12
|
+
import { validateLedger, applyChapterSettlement } from "./ledger-manager.mjs";
|
|
13
|
+
import { formatAuditMarkdown, formatDoctorMarkdown } from "./formatter.mjs";
|
|
14
|
+
import { analyzeStyleProfile, formatStyleProfileMarkdown } from "./style-profiler.mjs";
|
|
15
|
+
import { formatChapterForPlatform, exportChapters } from "./exporter.mjs";
|
|
16
|
+
import { collectTextFiles } from "./calibrator.mjs";
|
|
17
|
+
|
|
18
|
+
const currentFile = fileURLToPath(import.meta.url);
|
|
19
|
+
const rootDir = path.resolve(path.dirname(currentFile), "..");
|
|
20
|
+
const pkgPath = path.resolve(rootDir, "package.json");
|
|
21
|
+
const SERVER_VERSION = JSON.parse(fs.readFileSync(pkgPath, "utf8")).version || "2.0.0";
|
|
22
|
+
const SUPPORTED_PROTOCOL_VERSION = "2024-11-05";
|
|
23
|
+
|
|
24
|
+
// 8 个阶段提示词清单(暴露为 MCP Prompts,传入 genre 时自动挂载对应流派剧本卡)
|
|
25
|
+
const PROMPT_FILES = [
|
|
26
|
+
{
|
|
27
|
+
name: "inkbone/style-architect",
|
|
28
|
+
description: "Stage 0: Define genre register contract, three-tier character voice matrix, and novel.json rules.",
|
|
29
|
+
file: "prompts/00-style-architect.md",
|
|
30
|
+
arguments: [
|
|
31
|
+
{ name: "genre", description: "Optional genre pack id (e.g. classical-xianxia, urban-realism)", required: false },
|
|
32
|
+
{ name: "premise", description: "Optional novel premise or outline summary", required: false },
|
|
33
|
+
],
|
|
34
|
+
},
|
|
35
|
+
{
|
|
36
|
+
name: "inkbone/beat-planner",
|
|
37
|
+
description: "Stage 1: Build scene beat sheet and information placement plan before drafting (pauses for approval).",
|
|
38
|
+
file: "prompts/01-beat-planner.md",
|
|
39
|
+
arguments: [
|
|
40
|
+
{ name: "genre", description: "Optional genre pack id to attach matching playbook", required: false },
|
|
41
|
+
{ name: "chapter", description: "Target chapter number", required: false },
|
|
42
|
+
],
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
name: "inkbone/draft-chapter",
|
|
46
|
+
description: "Stage 2: Render Chinese chapter prose directly from beat sheet with pure genre register and clear subjects.",
|
|
47
|
+
file: "prompts/02-paratactic-renderer.md",
|
|
48
|
+
arguments: [
|
|
49
|
+
{ name: "genre", description: "Optional genre pack id to attach matching playbook", required: false },
|
|
50
|
+
{ name: "chapter", description: "Target chapter number", required: false },
|
|
51
|
+
],
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
name: "inkbone/targeted-rewriter",
|
|
55
|
+
description: "Stage 4: Perform surgical line-level edits on audit targets and verified review items without rewriting clean prose.",
|
|
56
|
+
file: "prompts/03-targeted-rewriter.md",
|
|
57
|
+
arguments: [
|
|
58
|
+
{ name: "genre", description: "Optional genre pack id", required: false },
|
|
59
|
+
],
|
|
60
|
+
},
|
|
61
|
+
{
|
|
62
|
+
name: "inkbone/evidence-reviewer",
|
|
63
|
+
description: "Stage 3a: Grounded continuity, timeline, physical-logic, and motivation review with verbatim quote enforcement.",
|
|
64
|
+
file: "prompts/04-evidence-reviewer.md",
|
|
65
|
+
arguments: [],
|
|
66
|
+
},
|
|
67
|
+
{
|
|
68
|
+
name: "inkbone/reader-simulator",
|
|
69
|
+
description: "Stage 3b: Dual-persona cold-reader & genre-veteran simulation producing verifiable JSON.",
|
|
70
|
+
file: "prompts/05-reader-simulator.md",
|
|
71
|
+
arguments: [
|
|
72
|
+
{ name: "persona", description: "cold or veteran", required: false },
|
|
73
|
+
],
|
|
74
|
+
},
|
|
75
|
+
{
|
|
76
|
+
name: "inkbone/ledger-importer",
|
|
77
|
+
description: "Stage 6: Reverse-engineer a non-destructive ledger.json from existing chapters without inventing lore.",
|
|
78
|
+
file: "prompts/06-ledger-importer.md",
|
|
79
|
+
arguments: [],
|
|
80
|
+
},
|
|
81
|
+
{
|
|
82
|
+
name: "inkbone/chapter-settler",
|
|
83
|
+
description: "Stage 5: Produce a post-chapter settlement JSON patch to update snapshots, summaries, and foreshadowing.",
|
|
84
|
+
file: "prompts/07-chapter-settler.md",
|
|
85
|
+
arguments: [
|
|
86
|
+
{ name: "chapter", description: "Completed chapter number to settle", required: false },
|
|
87
|
+
],
|
|
88
|
+
},
|
|
89
|
+
];
|
|
90
|
+
|
|
91
|
+
export const MCP_PROMPTS = PROMPT_FILES.map(({ name, description, arguments: args }) => ({
|
|
92
|
+
name,
|
|
93
|
+
description,
|
|
94
|
+
arguments: args,
|
|
95
|
+
}));
|
|
96
|
+
|
|
97
|
+
// 11 份只读写作知识库资源(9 份题材剧本卡 + 微技法 + 正反例对照)
|
|
98
|
+
const GENRE_PLAYBOOK_IDS = [
|
|
99
|
+
"classical-xianxia",
|
|
100
|
+
"historical-court",
|
|
101
|
+
"wuxia-jianghu",
|
|
102
|
+
"mystery-thriller",
|
|
103
|
+
"urban-realism",
|
|
104
|
+
"scifi-wasteland",
|
|
105
|
+
"light-fantasy",
|
|
106
|
+
"romance-emotional",
|
|
107
|
+
"general-clean",
|
|
108
|
+
];
|
|
109
|
+
|
|
110
|
+
const RESOURCE_ENTRIES = [
|
|
111
|
+
...GENRE_PLAYBOOK_IDS.map((genreId) => ({
|
|
112
|
+
uri: `inkbone://playbooks/${genreId}`,
|
|
113
|
+
name: `Playbook: ${genreId}`,
|
|
114
|
+
description: `Genre craft playbook, tropes to avoid, props, and chapter hooks for ${genreId}.`,
|
|
115
|
+
mimeType: "text/markdown",
|
|
116
|
+
file: `resources/genre_playbooks/${genreId}.md`,
|
|
117
|
+
})),
|
|
118
|
+
{
|
|
119
|
+
uri: "inkbone://craft/micro-techniques",
|
|
120
|
+
name: "Fiction Craft Micro-Techniques & Revision Lookup",
|
|
121
|
+
description: "Action-reaction beats, 80/20 climax framing, multi-purpose foreshadowing, and 9-symptom troubleshooting table.",
|
|
122
|
+
mimeType: "text/markdown",
|
|
123
|
+
file: "resources/micro_techniques.md",
|
|
124
|
+
},
|
|
125
|
+
{
|
|
126
|
+
uri: "inkbone://craft/bad-vs-good-cases",
|
|
127
|
+
name: "8 Before/After Prose Revision Cases",
|
|
128
|
+
description: "Side-by-side examples of cutting micro-action bloat, late-in/early-out dialogue, and preserving flow.",
|
|
129
|
+
mimeType: "text/markdown",
|
|
130
|
+
file: "resources/bad_vs_good_cases.md",
|
|
131
|
+
},
|
|
132
|
+
];
|
|
133
|
+
|
|
134
|
+
export const MCP_RESOURCES = RESOURCE_ENTRIES.map(({ uri, name, description, mimeType }) => ({
|
|
135
|
+
uri,
|
|
136
|
+
name,
|
|
137
|
+
description,
|
|
138
|
+
mimeType,
|
|
139
|
+
}));
|
|
140
|
+
|
|
141
|
+
// 暴露给 MCP 客户端的 9 个结构化工具声明与参数 Schema
|
|
142
|
+
export const MCP_TOOLS = [
|
|
143
|
+
{
|
|
144
|
+
name: "inkbone_packet",
|
|
145
|
+
description:
|
|
146
|
+
"Compile a spoiler-safe drafting context packet for chapter N from ledger.json (redacts unrevealed fullTruth and locked futureBlueprints, filters closed foreshadowing, and optionally scopes characterSnapshots).",
|
|
147
|
+
inputSchema: {
|
|
148
|
+
type: "object",
|
|
149
|
+
properties: {
|
|
150
|
+
ledgerPath: { type: "string", description: "Path to ledger.json" },
|
|
151
|
+
ledger: { type: "object", description: "Inline ledger object (alternative to ledgerPath)" },
|
|
152
|
+
chapter: { type: "number", description: "Target chapter number (>= 1)" },
|
|
153
|
+
prevPath: { type: "string", description: "Optional path to previous chapter markdown" },
|
|
154
|
+
prevText: { type: "string", description: "Optional inline previous chapter text" },
|
|
155
|
+
activeCharacters: {
|
|
156
|
+
type: "array",
|
|
157
|
+
items: { type: "string" },
|
|
158
|
+
description: "Optional active character list to prune characterSnapshots",
|
|
159
|
+
},
|
|
160
|
+
includeClosedForeshadowing: { type: "boolean" },
|
|
161
|
+
},
|
|
162
|
+
required: ["chapter"],
|
|
163
|
+
},
|
|
164
|
+
},
|
|
165
|
+
{
|
|
166
|
+
name: "inkbone_audit",
|
|
167
|
+
description:
|
|
168
|
+
"Run InkBone deterministic chapter audit (ledger boundaries, deceased-character guard, genre register, Traditional/Simplified script variant, stock phrases, density tics, degeneration, and subject continuity).",
|
|
169
|
+
inputSchema: {
|
|
170
|
+
type: "object",
|
|
171
|
+
properties: {
|
|
172
|
+
filePath: { type: "string", description: "Path to chapter .md/.txt file" },
|
|
173
|
+
text: { type: "string", description: "Inline chapter prose (alternative to filePath)" },
|
|
174
|
+
genre: { type: "string", description: "Genre pack id (e.g. classical-xianxia, urban-realism)" },
|
|
175
|
+
preset: { type: "string", description: "Optional preset id" },
|
|
176
|
+
variant: { type: "string", enum: ["auto", "zh-hans", "zh-hant"], description: "Script variant (default auto)" },
|
|
177
|
+
ledgerPath: { type: "string", description: "Optional path to ledger.json" },
|
|
178
|
+
chapter: { type: "number", description: "Optional chapter number for ledger boundary verification" },
|
|
179
|
+
prevPath: { type: "string", description: "Optional previous chapter path for echo check" },
|
|
180
|
+
outlinePath: { type: "string", description: "Optional chapter outline path for outline-copy check" },
|
|
181
|
+
characterNames: {
|
|
182
|
+
type: "array",
|
|
183
|
+
items: { type: "string" },
|
|
184
|
+
description: "Optional character names for subject continuity check",
|
|
185
|
+
},
|
|
186
|
+
skipLength: { type: "boolean", description: "Skip chapter word-count gate" },
|
|
187
|
+
strict: { type: "boolean", description: "Fail on warnings/info too" },
|
|
188
|
+
noProject: { type: "boolean", description: "Ignore upward novel.json discovery" },
|
|
189
|
+
format: { type: "string", enum: ["json", "md"], description: "Output format (default md)" },
|
|
190
|
+
lang: { type: "string", enum: ["zh", "en"], description: "Display language for md format (default zh)" },
|
|
191
|
+
},
|
|
192
|
+
},
|
|
193
|
+
},
|
|
194
|
+
{
|
|
195
|
+
name: "inkbone_doctor",
|
|
196
|
+
description:
|
|
197
|
+
"Recursively diagnose a chapter file or novel folder with automatic project config, genre detection, and optional incremental --chapters filtering.",
|
|
198
|
+
inputSchema: {
|
|
199
|
+
type: "object",
|
|
200
|
+
properties: {
|
|
201
|
+
paths: {
|
|
202
|
+
type: "array",
|
|
203
|
+
items: { type: "string" },
|
|
204
|
+
description: "One or more chapter files or directories",
|
|
205
|
+
},
|
|
206
|
+
genre: { type: "string" },
|
|
207
|
+
variant: { type: "string", enum: ["auto", "zh-hans", "zh-hant"] },
|
|
208
|
+
chapters: { type: "string", description: "Optional chapter filter spec (e.g. 40-45,48)" },
|
|
209
|
+
ledgerPath: { type: "string" },
|
|
210
|
+
skipLength: { type: "boolean" },
|
|
211
|
+
format: { type: "string", enum: ["json", "md"] },
|
|
212
|
+
lang: { type: "string", enum: ["zh", "en"] },
|
|
213
|
+
},
|
|
214
|
+
required: ["paths"],
|
|
215
|
+
},
|
|
216
|
+
},
|
|
217
|
+
{
|
|
218
|
+
name: "inkbone_normalize",
|
|
219
|
+
description:
|
|
220
|
+
"Deterministically clean stray Markdown emphasis asterisks, divider lines, and ellipses (preserving dialogue em-dashes and whitelisted literals).",
|
|
221
|
+
inputSchema: {
|
|
222
|
+
type: "object",
|
|
223
|
+
properties: {
|
|
224
|
+
text: { type: "string", description: "Inline text to normalize" },
|
|
225
|
+
paths: {
|
|
226
|
+
type: "array",
|
|
227
|
+
items: { type: "string" },
|
|
228
|
+
description: "Files or directories to normalize in place (unless checkOnly is true)",
|
|
229
|
+
},
|
|
230
|
+
checkOnly: { type: "boolean", description: "Preview without writing files" },
|
|
231
|
+
stripBold: { type: "boolean", description: "Strip stray **bold** emphasis (default true)" },
|
|
232
|
+
fixEmDash: { type: "boolean", description: "Replace narration em-dashes" },
|
|
233
|
+
},
|
|
234
|
+
},
|
|
235
|
+
},
|
|
236
|
+
{
|
|
237
|
+
name: "inkbone_verify_review",
|
|
238
|
+
description:
|
|
239
|
+
"Verify that every quote in a logic or reader review JSON exists verbatim in the chapter text and block unauthorized style-interference commentary.",
|
|
240
|
+
inputSchema: {
|
|
241
|
+
type: "object",
|
|
242
|
+
properties: {
|
|
243
|
+
chapterPath: { type: "string" },
|
|
244
|
+
chapterText: { type: "string" },
|
|
245
|
+
reviewPath: { type: "string" },
|
|
246
|
+
review: { type: "object" },
|
|
247
|
+
},
|
|
248
|
+
},
|
|
249
|
+
},
|
|
250
|
+
{
|
|
251
|
+
name: "inkbone_check_ledger",
|
|
252
|
+
description:
|
|
253
|
+
"Validate ledger.json health: duplicate/missing chapters, invalid revealChapter order, empty characterNames, empty summaries, and overdue active foreshadowing.",
|
|
254
|
+
inputSchema: {
|
|
255
|
+
type: "object",
|
|
256
|
+
properties: {
|
|
257
|
+
ledgerPath: { type: "string" },
|
|
258
|
+
ledger: { type: "object" },
|
|
259
|
+
currentChapter: { type: "number" },
|
|
260
|
+
overdueThreshold: { type: "number" },
|
|
261
|
+
},
|
|
262
|
+
},
|
|
263
|
+
},
|
|
264
|
+
{
|
|
265
|
+
name: "inkbone_settle",
|
|
266
|
+
description:
|
|
267
|
+
"Non-destructively merge a post-chapter settlement patch (summary, characterSnapshots updates, foreshadowing transitions, knowledge updates) into ledger.json.",
|
|
268
|
+
inputSchema: {
|
|
269
|
+
type: "object",
|
|
270
|
+
properties: {
|
|
271
|
+
ledgerPath: { type: "string", description: "Path to ledger.json to read and update" },
|
|
272
|
+
ledger: { type: "object", description: "Inline ledger object (when dryRun or in-memory)" },
|
|
273
|
+
patch: { type: "object", description: "Settlement JSON patch containing chapterNumber and updates" },
|
|
274
|
+
patchPath: { type: "string", description: "Optional path to settlement JSON patch file" },
|
|
275
|
+
dryRun: { type: "boolean", description: "Preview diff without writing to ledgerPath" },
|
|
276
|
+
},
|
|
277
|
+
},
|
|
278
|
+
},
|
|
279
|
+
{
|
|
280
|
+
name: "inkbone_style_profile",
|
|
281
|
+
description:
|
|
282
|
+
"Compute a copyright-safe statistical style profile (quantiles, nearest preset, and suggested customGates for novel.json) from sample texts or directories without outputting any source prose.",
|
|
283
|
+
inputSchema: {
|
|
284
|
+
type: "object",
|
|
285
|
+
properties: {
|
|
286
|
+
texts: { type: "array", items: { type: "string" }, description: "Inline sample texts" },
|
|
287
|
+
paths: { type: "array", items: { type: "string" }, description: "Files or directories of sample prose" },
|
|
288
|
+
label: { type: "string" },
|
|
289
|
+
format: { type: "string", enum: ["json", "md"] },
|
|
290
|
+
lang: { type: "string", enum: ["zh", "en"] },
|
|
291
|
+
},
|
|
292
|
+
},
|
|
293
|
+
},
|
|
294
|
+
{
|
|
295
|
+
name: "inkbone_export",
|
|
296
|
+
description:
|
|
297
|
+
"Clean Markdown artifacts and format chapter(s) for major Chinese web-fiction platforms (qidian, fanqie, qimao, jjwxc) with length checks.",
|
|
298
|
+
inputSchema: {
|
|
299
|
+
type: "object",
|
|
300
|
+
properties: {
|
|
301
|
+
text: { type: "string", description: "Inline single chapter text" },
|
|
302
|
+
paths: { type: "array", items: { type: "string" }, description: "Chapter files or directories to export" },
|
|
303
|
+
platform: { type: "string", enum: ["qidian", "fanqie", "qimao", "jjwxc"] },
|
|
304
|
+
indent: { type: "boolean", description: "Apply full-width two-space paragraph indentation" },
|
|
305
|
+
outDir: { type: "string", description: "Optional output directory for per-chapter .txt files" },
|
|
306
|
+
mergeOut: { type: "string", description: "Optional output file for merged volume .txt" },
|
|
307
|
+
checkOnly: { type: "boolean", description: "Dry-run length and formatting check without writing files" },
|
|
308
|
+
},
|
|
309
|
+
},
|
|
310
|
+
},
|
|
311
|
+
];
|
|
312
|
+
|
|
313
|
+
// 辅助读取台账对象(支持文件路径或内联对象)
|
|
314
|
+
function resolveLedgerArg(args) {
|
|
315
|
+
if (args.ledger && typeof args.ledger === "object") {
|
|
316
|
+
return { ledger: args.ledger, ledgerPath: args.ledgerPath ? path.resolve(args.ledgerPath) : null };
|
|
317
|
+
}
|
|
318
|
+
if (typeof args.ledgerPath === "string" && args.ledgerPath.trim()) {
|
|
319
|
+
const abs = path.resolve(args.ledgerPath);
|
|
320
|
+
if (!fs.existsSync(abs)) {
|
|
321
|
+
throw new Error(`Ledger file not found: ${abs}`);
|
|
322
|
+
}
|
|
323
|
+
return { ledger: JSON.parse(fs.readFileSync(abs, "utf8")), ledgerPath: abs };
|
|
324
|
+
}
|
|
325
|
+
throw new Error("Provide either ledgerPath or inline ledger object.");
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// 执行单个 MCP 工具调用并返回标准 content 响应
|
|
329
|
+
function executeToolCall(name, rawArgs = {}) {
|
|
330
|
+
const args = rawArgs && typeof rawArgs === "object" ? rawArgs : {};
|
|
331
|
+
|
|
332
|
+
if (name === "inkbone_packet") {
|
|
333
|
+
const { ledger } = resolveLedgerArg(args);
|
|
334
|
+
const prevText =
|
|
335
|
+
typeof args.prevText === "string"
|
|
336
|
+
? args.prevText
|
|
337
|
+
: typeof args.prevPath === "string" && fs.existsSync(path.resolve(args.prevPath))
|
|
338
|
+
? fs.readFileSync(path.resolve(args.prevPath), "utf8")
|
|
339
|
+
: "";
|
|
340
|
+
const packet = compileBoundaryPacket(ledger, Number(args.chapter), prevText, {
|
|
341
|
+
activeCharacters: args.activeCharacters,
|
|
342
|
+
includeClosedForeshadowing: Boolean(args.includeClosedForeshadowing),
|
|
343
|
+
});
|
|
344
|
+
return {
|
|
345
|
+
content: [{ type: "text", text: JSON.stringify(packet, null, 2) }],
|
|
346
|
+
structuredContent: packet,
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
if (name === "inkbone_audit") {
|
|
351
|
+
let text = typeof args.text === "string" ? args.text : null;
|
|
352
|
+
let project = null;
|
|
353
|
+
let fileName = null;
|
|
354
|
+
if (text === null && typeof args.filePath === "string") {
|
|
355
|
+
const abs = path.resolve(args.filePath);
|
|
356
|
+
if (!fs.existsSync(abs)) throw new Error(`Chapter file not found: ${abs}`);
|
|
357
|
+
text = fs.readFileSync(abs, "utf8");
|
|
358
|
+
fileName = path.basename(abs);
|
|
359
|
+
if (!args.noProject) {
|
|
360
|
+
const cfgPath = findProjectConfig(path.dirname(abs));
|
|
361
|
+
if (cfgPath) project = loadProjectConfig(cfgPath);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
if (text === null) {
|
|
365
|
+
throw new Error("Provide either filePath or text for inkbone_audit.");
|
|
366
|
+
}
|
|
367
|
+
let ledger = null;
|
|
368
|
+
if (typeof args.ledgerPath === "string" && args.ledgerPath.trim()) {
|
|
369
|
+
ledger = JSON.parse(fs.readFileSync(path.resolve(args.ledgerPath), "utf8"));
|
|
370
|
+
} else if (project?.ledgerFile && fs.existsSync(project.ledgerFile)) {
|
|
371
|
+
ledger = JSON.parse(fs.readFileSync(project.ledgerFile, "utf8"));
|
|
372
|
+
}
|
|
373
|
+
const prevText =
|
|
374
|
+
typeof args.prevPath === "string" && fs.existsSync(path.resolve(args.prevPath))
|
|
375
|
+
? fs.readFileSync(path.resolve(args.prevPath), "utf8")
|
|
376
|
+
: "";
|
|
377
|
+
const outlineText =
|
|
378
|
+
typeof args.outlinePath === "string" && fs.existsSync(path.resolve(args.outlinePath))
|
|
379
|
+
? fs.readFileSync(path.resolve(args.outlinePath), "utf8")
|
|
380
|
+
: "";
|
|
381
|
+
|
|
382
|
+
const report = auditChapterText(text, {
|
|
383
|
+
genre: args.genre || project?.genre || null,
|
|
384
|
+
presetName: args.preset || project?.preset || null,
|
|
385
|
+
customGates: project?.customGates || null,
|
|
386
|
+
variant: args.variant || project?.variant || "auto",
|
|
387
|
+
projectRules: project ? project.rules : null,
|
|
388
|
+
ledger,
|
|
389
|
+
characterNames: Array.isArray(args.characterNames) ? args.characterNames : undefined,
|
|
390
|
+
chapterNumber: args.chapter != null ? Number(args.chapter) : null,
|
|
391
|
+
previousChapterText: prevText,
|
|
392
|
+
outlineText,
|
|
393
|
+
skipLengthGate: Boolean(args.skipLength),
|
|
394
|
+
strict: Boolean(args.strict),
|
|
395
|
+
});
|
|
396
|
+
const outText =
|
|
397
|
+
args.format === "json"
|
|
398
|
+
? JSON.stringify(report, null, 2)
|
|
399
|
+
: formatAuditMarkdown(report, { lang: args.lang || "zh", fileName });
|
|
400
|
+
return {
|
|
401
|
+
content: [{ type: "text", text: outText }],
|
|
402
|
+
structuredContent: report,
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
if (name === "inkbone_doctor") {
|
|
407
|
+
const targets = Array.isArray(args.paths) ? args.paths : [];
|
|
408
|
+
if (targets.length === 0) {
|
|
409
|
+
throw new Error("paths array with at least one file or directory is required.");
|
|
410
|
+
}
|
|
411
|
+
const firstAbs = path.resolve(targets[0]);
|
|
412
|
+
const startDir =
|
|
413
|
+
fs.existsSync(firstAbs) && fs.statSync(firstAbs).isDirectory()
|
|
414
|
+
? firstAbs
|
|
415
|
+
: path.dirname(firstAbs);
|
|
416
|
+
const cfgPath = findProjectConfig(startDir);
|
|
417
|
+
const project = cfgPath ? loadProjectConfig(cfgPath) : null;
|
|
418
|
+
let ledger = null;
|
|
419
|
+
if (typeof args.ledgerPath === "string" && args.ledgerPath.trim()) {
|
|
420
|
+
ledger = JSON.parse(fs.readFileSync(path.resolve(args.ledgerPath), "utf8"));
|
|
421
|
+
} else if (project?.ledgerFile && fs.existsSync(project.ledgerFile)) {
|
|
422
|
+
ledger = JSON.parse(fs.readFileSync(project.ledgerFile, "utf8"));
|
|
423
|
+
}
|
|
424
|
+
const diag = diagnoseProject(targets, {
|
|
425
|
+
genre: args.genre || project?.genre || undefined,
|
|
426
|
+
presetName: project?.preset || undefined,
|
|
427
|
+
customGates: project?.customGates || null,
|
|
428
|
+
variant: args.variant || project?.variant || "auto",
|
|
429
|
+
chapterFilter: args.chapters || undefined,
|
|
430
|
+
projectRules: project ? project.rules : null,
|
|
431
|
+
genreSource: !args.genre && project?.genre ? "project" : undefined,
|
|
432
|
+
ledger,
|
|
433
|
+
skipLengthGate: Boolean(args.skipLength),
|
|
434
|
+
});
|
|
435
|
+
const outText =
|
|
436
|
+
args.format === "json"
|
|
437
|
+
? JSON.stringify(diag, null, 2)
|
|
438
|
+
: formatDoctorMarkdown(diag, { lang: args.lang || "zh" });
|
|
439
|
+
return {
|
|
440
|
+
content: [{ type: "text", text: outText }],
|
|
441
|
+
structuredContent: diag,
|
|
442
|
+
};
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
if (name === "inkbone_normalize") {
|
|
446
|
+
const stripBold = args.stripBold !== undefined ? Boolean(args.stripBold) : true;
|
|
447
|
+
const fixEmDash = Boolean(args.fixEmDash);
|
|
448
|
+
if (typeof args.text === "string") {
|
|
449
|
+
const res = normalizeProseText(args.text, {
|
|
450
|
+
stripMarkdownEmphasis: stripBold,
|
|
451
|
+
fixNarrationEmDash: fixEmDash,
|
|
452
|
+
});
|
|
453
|
+
return {
|
|
454
|
+
content: [{ type: "text", text: JSON.stringify(res, null, 2) }],
|
|
455
|
+
structuredContent: res,
|
|
456
|
+
};
|
|
457
|
+
}
|
|
458
|
+
if (Array.isArray(args.paths) && args.paths.length > 0) {
|
|
459
|
+
const res = normalizeFiles(args.paths, {
|
|
460
|
+
check: Boolean(args.checkOnly),
|
|
461
|
+
stripMarkdownEmphasis: stripBold,
|
|
462
|
+
fixNarrationEmDash: fixEmDash,
|
|
463
|
+
});
|
|
464
|
+
return {
|
|
465
|
+
content: [{ type: "text", text: JSON.stringify(res, null, 2) }],
|
|
466
|
+
structuredContent: res,
|
|
467
|
+
};
|
|
468
|
+
}
|
|
469
|
+
throw new Error("Provide either text or paths for inkbone_normalize.");
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
if (name === "inkbone_verify_review") {
|
|
473
|
+
const chapterText =
|
|
474
|
+
typeof args.chapterText === "string"
|
|
475
|
+
? args.chapterText
|
|
476
|
+
: typeof args.chapterPath === "string"
|
|
477
|
+
? fs.readFileSync(path.resolve(args.chapterPath), "utf8")
|
|
478
|
+
: null;
|
|
479
|
+
const review =
|
|
480
|
+
args.review && typeof args.review === "object"
|
|
481
|
+
? args.review
|
|
482
|
+
: typeof args.reviewPath === "string"
|
|
483
|
+
? JSON.parse(fs.readFileSync(path.resolve(args.reviewPath), "utf8"))
|
|
484
|
+
: null;
|
|
485
|
+
if (chapterText === null || review === null) {
|
|
486
|
+
throw new Error("Provide chapterText/chapterPath and review/reviewPath.");
|
|
487
|
+
}
|
|
488
|
+
const validation = validateEvidenceReview(chapterText, review);
|
|
489
|
+
return {
|
|
490
|
+
content: [{ type: "text", text: JSON.stringify(validation, null, 2) }],
|
|
491
|
+
structuredContent: validation,
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
if (name === "inkbone_check_ledger") {
|
|
496
|
+
const { ledger } = resolveLedgerArg(args);
|
|
497
|
+
const report = validateLedger(ledger, {
|
|
498
|
+
currentChapter: args.currentChapter,
|
|
499
|
+
overdueThreshold: args.overdueThreshold,
|
|
500
|
+
});
|
|
501
|
+
return {
|
|
502
|
+
content: [{ type: "text", text: JSON.stringify(report, null, 2) }],
|
|
503
|
+
structuredContent: report,
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
if (name === "inkbone_settle") {
|
|
508
|
+
const { ledger, ledgerPath } = resolveLedgerArg(args);
|
|
509
|
+
const patch =
|
|
510
|
+
args.patch && typeof args.patch === "object"
|
|
511
|
+
? args.patch
|
|
512
|
+
: typeof args.patchPath === "string"
|
|
513
|
+
? JSON.parse(fs.readFileSync(path.resolve(args.patchPath), "utf8"))
|
|
514
|
+
: null;
|
|
515
|
+
if (!patch) {
|
|
516
|
+
throw new Error("Provide either patch object or patchPath for inkbone_settle.");
|
|
517
|
+
}
|
|
518
|
+
const settled = applyChapterSettlement(ledger, patch);
|
|
519
|
+
const wroteFile = Boolean(ledgerPath && !args.dryRun);
|
|
520
|
+
if (wroteFile) {
|
|
521
|
+
fs.writeFileSync(ledgerPath, JSON.stringify(settled.ledger, null, 2) + "\n");
|
|
522
|
+
}
|
|
523
|
+
const payload = {
|
|
524
|
+
wroteFile,
|
|
525
|
+
ledgerPath,
|
|
526
|
+
diff: settled.diff,
|
|
527
|
+
health: validateLedger(settled.ledger, { currentChapter: settled.diff.chapterNumber }),
|
|
528
|
+
};
|
|
529
|
+
return {
|
|
530
|
+
content: [{ type: "text", text: JSON.stringify(payload, null, 2) }],
|
|
531
|
+
structuredContent: payload,
|
|
532
|
+
};
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
if (name === "inkbone_style_profile") {
|
|
536
|
+
let texts = Array.isArray(args.texts) ? args.texts.filter((t) => typeof t === "string") : [];
|
|
537
|
+
if (texts.length === 0 && Array.isArray(args.paths) && args.paths.length > 0) {
|
|
538
|
+
const files = collectTextFiles(args.paths);
|
|
539
|
+
texts = files.map((f) => fs.readFileSync(f, "utf8"));
|
|
540
|
+
}
|
|
541
|
+
if (texts.length === 0) {
|
|
542
|
+
throw new Error("Provide either texts array or paths for inkbone_style_profile.");
|
|
543
|
+
}
|
|
544
|
+
const profile = analyzeStyleProfile(texts, { label: args.label || "" });
|
|
545
|
+
const outText =
|
|
546
|
+
args.format === "json"
|
|
547
|
+
? JSON.stringify(profile, null, 2)
|
|
548
|
+
: formatStyleProfileMarkdown(profile, { lang: args.lang || "zh" });
|
|
549
|
+
return {
|
|
550
|
+
content: [{ type: "text", text: outText }],
|
|
551
|
+
structuredContent: profile,
|
|
552
|
+
};
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
if (name === "inkbone_export") {
|
|
556
|
+
const platform = args.platform || "qidian";
|
|
557
|
+
if (typeof args.text === "string") {
|
|
558
|
+
const res = formatChapterForPlatform(args.text, {
|
|
559
|
+
platform,
|
|
560
|
+
indent: args.indent,
|
|
561
|
+
});
|
|
562
|
+
return {
|
|
563
|
+
content: [{ type: "text", text: res.output }],
|
|
564
|
+
structuredContent: res,
|
|
565
|
+
};
|
|
566
|
+
}
|
|
567
|
+
if (Array.isArray(args.paths) && args.paths.length > 0) {
|
|
568
|
+
const res = exportChapters(args.paths, {
|
|
569
|
+
platform,
|
|
570
|
+
indent: args.indent,
|
|
571
|
+
outDir: args.outDir,
|
|
572
|
+
mergeOut: args.mergeOut,
|
|
573
|
+
check: Boolean(args.checkOnly),
|
|
574
|
+
});
|
|
575
|
+
return {
|
|
576
|
+
content: [{ type: "text", text: JSON.stringify(res, null, 2) }],
|
|
577
|
+
structuredContent: res,
|
|
578
|
+
};
|
|
579
|
+
}
|
|
580
|
+
throw new Error("Provide either text or paths for inkbone_export.");
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
throw new Error(`Unknown MCP tool: ${name}`);
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
// 组装指定 MCP Prompt(如附带合法 genre 参数,自动拼接对应流派剧本卡)
|
|
587
|
+
function executePromptGet(name, rawArgs = {}) {
|
|
588
|
+
const entry = PROMPT_FILES.find((p) => p.name === name);
|
|
589
|
+
if (!entry) {
|
|
590
|
+
throw new Error(`Unknown MCP prompt: ${name}`);
|
|
591
|
+
}
|
|
592
|
+
const promptPath = path.resolve(rootDir, entry.file);
|
|
593
|
+
if (!fs.existsSync(promptPath)) {
|
|
594
|
+
throw new Error(`Prompt file missing: ${entry.file}`);
|
|
595
|
+
}
|
|
596
|
+
const promptBody = fs.readFileSync(promptPath, "utf8");
|
|
597
|
+
const args = rawArgs && typeof rawArgs === "object" ? rawArgs : {};
|
|
598
|
+
const messages = [
|
|
599
|
+
{
|
|
600
|
+
role: "user",
|
|
601
|
+
content: { type: "text", text: promptBody },
|
|
602
|
+
},
|
|
603
|
+
];
|
|
604
|
+
|
|
605
|
+
// 附加上下文参数说明与可选对应流派剧本卡
|
|
606
|
+
const contextParts = [];
|
|
607
|
+
if (args.chapter != null && String(args.chapter).trim()) {
|
|
608
|
+
contextParts.push(`Target chapter: ${args.chapter}`);
|
|
609
|
+
}
|
|
610
|
+
if (typeof args.persona === "string" && args.persona.trim()) {
|
|
611
|
+
contextParts.push(`Reader persona focus: ${args.persona}`);
|
|
612
|
+
}
|
|
613
|
+
if (typeof args.premise === "string" && args.premise.trim()) {
|
|
614
|
+
contextParts.push(`Premise:\n${args.premise}`);
|
|
615
|
+
}
|
|
616
|
+
if (typeof args.genre === "string" && GENRE_PLAYBOOK_IDS.includes(args.genre)) {
|
|
617
|
+
const pbPath = path.resolve(rootDir, `resources/genre_playbooks/${args.genre}.md`);
|
|
618
|
+
if (fs.existsSync(pbPath)) {
|
|
619
|
+
contextParts.push(
|
|
620
|
+
`Attached Genre Playbook (${args.genre}):\n\n${fs.readFileSync(pbPath, "utf8")}`
|
|
621
|
+
);
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
if (contextParts.length > 0) {
|
|
625
|
+
messages.push({
|
|
626
|
+
role: "user",
|
|
627
|
+
content: { type: "text", text: contextParts.join("\n\n---\n\n") },
|
|
628
|
+
});
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
return {
|
|
632
|
+
description: entry.description,
|
|
633
|
+
messages,
|
|
634
|
+
};
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
// 读取指定的 MCP Resource 只读 Markdown 内容
|
|
638
|
+
function executeResourceRead(uri) {
|
|
639
|
+
const entry = RESOURCE_ENTRIES.find((r) => r.uri === uri);
|
|
640
|
+
if (!entry) {
|
|
641
|
+
throw new Error(`Unknown MCP resource URI: ${uri}`);
|
|
642
|
+
}
|
|
643
|
+
const absPath = path.resolve(rootDir, entry.file);
|
|
644
|
+
if (!fs.existsSync(absPath)) {
|
|
645
|
+
throw new Error(`Resource file missing: ${entry.file}`);
|
|
646
|
+
}
|
|
647
|
+
return {
|
|
648
|
+
contents: [
|
|
649
|
+
{
|
|
650
|
+
uri: entry.uri,
|
|
651
|
+
mimeType: entry.mimeType,
|
|
652
|
+
text: fs.readFileSync(absPath, "utf8"),
|
|
653
|
+
},
|
|
654
|
+
],
|
|
655
|
+
};
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
// 处理单条 JSON-RPC 2.0 消息并返回响应对象(通知类消息返回 null)
|
|
659
|
+
export function handleMcpMessage(msg) {
|
|
660
|
+
if (!msg || typeof msg !== "object" || msg.jsonrpc !== "2.0") {
|
|
661
|
+
return {
|
|
662
|
+
jsonrpc: "2.0",
|
|
663
|
+
id: msg?.id ?? null,
|
|
664
|
+
error: { code: -32600, message: "Invalid JSON-RPC 2.0 request." },
|
|
665
|
+
};
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
const { id, method, params } = msg;
|
|
669
|
+
const isNotification = id === undefined || id === null;
|
|
670
|
+
|
|
671
|
+
if (method === "notifications/initialized" || method === "notifications/cancelled") {
|
|
672
|
+
return null;
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
if (method === "initialize") {
|
|
676
|
+
const requestedVersion = params?.protocolVersion || SUPPORTED_PROTOCOL_VERSION;
|
|
677
|
+
return {
|
|
678
|
+
jsonrpc: "2.0",
|
|
679
|
+
id,
|
|
680
|
+
result: {
|
|
681
|
+
protocolVersion: requestedVersion,
|
|
682
|
+
capabilities: {
|
|
683
|
+
tools: { listChanged: false },
|
|
684
|
+
prompts: { listChanged: false },
|
|
685
|
+
resources: { subscribe: false, listChanged: false },
|
|
686
|
+
},
|
|
687
|
+
serverInfo: {
|
|
688
|
+
name: "inkbone",
|
|
689
|
+
version: SERVER_VERSION,
|
|
690
|
+
},
|
|
691
|
+
},
|
|
692
|
+
};
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
if (method === "ping") {
|
|
696
|
+
return { jsonrpc: "2.0", id, result: {} };
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
if (method === "tools/list") {
|
|
700
|
+
return { jsonrpc: "2.0", id, result: { tools: MCP_TOOLS } };
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
if (method === "tools/call") {
|
|
704
|
+
const toolName = params?.name;
|
|
705
|
+
if (!toolName || typeof toolName !== "string") {
|
|
706
|
+
return {
|
|
707
|
+
jsonrpc: "2.0",
|
|
708
|
+
id,
|
|
709
|
+
error: { code: -32602, message: "Missing required params.name for tools/call." },
|
|
710
|
+
};
|
|
711
|
+
}
|
|
712
|
+
try {
|
|
713
|
+
const result = executeToolCall(toolName, params?.arguments || {});
|
|
714
|
+
return { jsonrpc: "2.0", id, result };
|
|
715
|
+
} catch (err) {
|
|
716
|
+
return {
|
|
717
|
+
jsonrpc: "2.0",
|
|
718
|
+
id,
|
|
719
|
+
result: {
|
|
720
|
+
isError: true,
|
|
721
|
+
content: [{ type: "text", text: `Error: ${err.message}` }],
|
|
722
|
+
},
|
|
723
|
+
};
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
if (method === "prompts/list") {
|
|
728
|
+
return { jsonrpc: "2.0", id, result: { prompts: MCP_PROMPTS } };
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
if (method === "prompts/get") {
|
|
732
|
+
const promptName = params?.name;
|
|
733
|
+
if (!promptName || typeof promptName !== "string") {
|
|
734
|
+
return {
|
|
735
|
+
jsonrpc: "2.0",
|
|
736
|
+
id,
|
|
737
|
+
error: { code: -32602, message: "Missing required params.name for prompts/get." },
|
|
738
|
+
};
|
|
739
|
+
}
|
|
740
|
+
try {
|
|
741
|
+
const result = executePromptGet(promptName, params?.arguments || {});
|
|
742
|
+
return { jsonrpc: "2.0", id, result };
|
|
743
|
+
} catch (err) {
|
|
744
|
+
return {
|
|
745
|
+
jsonrpc: "2.0",
|
|
746
|
+
id,
|
|
747
|
+
error: { code: -32602, message: err.message },
|
|
748
|
+
};
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
if (method === "resources/list") {
|
|
753
|
+
return { jsonrpc: "2.0", id, result: { resources: MCP_RESOURCES } };
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
if (method === "resources/read") {
|
|
757
|
+
const uri = params?.uri;
|
|
758
|
+
if (!uri || typeof uri !== "string") {
|
|
759
|
+
return {
|
|
760
|
+
jsonrpc: "2.0",
|
|
761
|
+
id,
|
|
762
|
+
error: { code: -32602, message: "Missing required params.uri for resources/read." },
|
|
763
|
+
};
|
|
764
|
+
}
|
|
765
|
+
try {
|
|
766
|
+
const result = executeResourceRead(uri);
|
|
767
|
+
return { jsonrpc: "2.0", id, result };
|
|
768
|
+
} catch (err) {
|
|
769
|
+
return {
|
|
770
|
+
jsonrpc: "2.0",
|
|
771
|
+
id,
|
|
772
|
+
error: { code: -32602, message: err.message },
|
|
773
|
+
};
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
if (isNotification) return null;
|
|
778
|
+
return {
|
|
779
|
+
jsonrpc: "2.0",
|
|
780
|
+
id,
|
|
781
|
+
error: { code: -32601, message: `Method not found: ${method}` },
|
|
782
|
+
};
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
// 启动基于标准输入输出的 MCP 服务器,自动探测 Content-Length 帧与 NDJSON 行帧
|
|
786
|
+
export function startMcpServer(inputStream = process.stdin, outputStream = process.stdout) {
|
|
787
|
+
let buffer = Buffer.alloc(0);
|
|
788
|
+
let framingMode = null;
|
|
789
|
+
|
|
790
|
+
const sendResponse = (payload) => {
|
|
791
|
+
if (!payload) return;
|
|
792
|
+
const json = JSON.stringify(payload);
|
|
793
|
+
if (framingMode === "content-length") {
|
|
794
|
+
const byteLen = Buffer.byteLength(json, "utf8");
|
|
795
|
+
outputStream.write(`Content-Length: ${byteLen}\r\n\r\n${json}`);
|
|
796
|
+
} else {
|
|
797
|
+
outputStream.write(`${json}\n`);
|
|
798
|
+
}
|
|
799
|
+
};
|
|
800
|
+
|
|
801
|
+
const processMessageText = (rawText) => {
|
|
802
|
+
const trimmed = rawText.trim();
|
|
803
|
+
if (!trimmed) return;
|
|
804
|
+
let parsed;
|
|
805
|
+
try {
|
|
806
|
+
parsed = JSON.parse(trimmed);
|
|
807
|
+
} catch {
|
|
808
|
+
sendResponse({
|
|
809
|
+
jsonrpc: "2.0",
|
|
810
|
+
id: null,
|
|
811
|
+
error: { code: -32700, message: "Parse error: invalid JSON." },
|
|
812
|
+
});
|
|
813
|
+
return;
|
|
814
|
+
}
|
|
815
|
+
const reply = handleMcpMessage(parsed);
|
|
816
|
+
if (reply) sendResponse(reply);
|
|
817
|
+
};
|
|
818
|
+
|
|
819
|
+
const drainBuffer = () => {
|
|
820
|
+
while (buffer.length > 0) {
|
|
821
|
+
const prefix = buffer.subarray(0, Math.min(buffer.length, 32)).toString("utf8");
|
|
822
|
+
if (/^Content-Length:/i.test(prefix)) {
|
|
823
|
+
framingMode = "content-length";
|
|
824
|
+
const headerEnd = buffer.indexOf("\r\n\r\n");
|
|
825
|
+
if (headerEnd === -1) return;
|
|
826
|
+
const headerText = buffer.subarray(0, headerEnd).toString("utf8");
|
|
827
|
+
const lenMatch = headerText.match(/Content-Length:\s*(\d+)/i);
|
|
828
|
+
if (!lenMatch) {
|
|
829
|
+
buffer = buffer.subarray(headerEnd + 4);
|
|
830
|
+
continue;
|
|
831
|
+
}
|
|
832
|
+
const contentLen = Number(lenMatch[1]);
|
|
833
|
+
const totalLen = headerEnd + 4 + contentLen;
|
|
834
|
+
if (buffer.length < totalLen) return;
|
|
835
|
+
const body = buffer.subarray(headerEnd + 4, totalLen).toString("utf8");
|
|
836
|
+
buffer = buffer.subarray(totalLen);
|
|
837
|
+
processMessageText(body);
|
|
838
|
+
} else {
|
|
839
|
+
const nlIdx = buffer.indexOf("\n");
|
|
840
|
+
if (nlIdx === -1) return;
|
|
841
|
+
if (!framingMode) framingMode = "ndjson";
|
|
842
|
+
const line = buffer.subarray(0, nlIdx).toString("utf8");
|
|
843
|
+
buffer = buffer.subarray(nlIdx + 1);
|
|
844
|
+
processMessageText(line);
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
};
|
|
848
|
+
|
|
849
|
+
inputStream.on("data", (chunk) => {
|
|
850
|
+
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, "utf8");
|
|
851
|
+
buffer = Buffer.concat([buffer, buf]);
|
|
852
|
+
drainBuffer();
|
|
853
|
+
});
|
|
854
|
+
|
|
855
|
+
inputStream.on("end", () => {
|
|
856
|
+
if (buffer.length > 0 && framingMode !== "content-length") {
|
|
857
|
+
processMessageText(buffer.toString("utf8"));
|
|
858
|
+
buffer = Buffer.alloc(0);
|
|
859
|
+
}
|
|
860
|
+
});
|
|
861
|
+
}
|