thesis-format-check-mcp 0.0.0-stage → 1.0.1

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/index.js ADDED
@@ -0,0 +1,88 @@
1
+ #!/usr/bin/env node
2
+ // 旭光云·论文格式助手 MCP · stdio(零依赖)
3
+ import readline from 'node:readline';
4
+ import fs from 'node:fs';
5
+ import { readDocx } from './lib/io.js';
6
+ import { check, VERDICT_NOTE } from './lib/thesis.js';
7
+
8
+ const NAME = 'thesis-format-check-mcp';
9
+ const VERSION = '1.0.0';
10
+
11
+ const TOOLS = [
12
+ {
13
+ name: 'check_thesis_format',
14
+ description:
15
+ '按 GB/T 7714—2015 与 GB/T 7713.1—2006 核验学位论文 .docx:参考文献著录要素与文献类型标识、作者超过 3 人是否用「等」、正文引文与文末条目是否对应、章节编号连续性与跳级、图表编号重复与断号、摘要字数与关键词个数、页边距与纸张。输出四态结论,每条问题带段落序号、实际值与应为值。只读不改文件。',
16
+ inputSchema: {
17
+ type: 'object',
18
+ properties: {
19
+ path: { type: 'string', description: '本地 .docx 论文绝对路径' },
20
+ },
21
+ required: ['path'],
22
+ },
23
+ },
24
+ ];
25
+
26
+ function brief(r) {
27
+ const L = [
28
+ `结论:${r.verdict} —— ${r.verdict_note}`,
29
+ `段落 ${r.stats.paragraphs} | 章节 ${r.stats.headings} | 参考文献 ${r.stats.refs} 条(正文引用 ${r.stats.cited} 处)| 图 ${r.stats.figures} | 表 ${r.stats.tables_captioned}`,
30
+ `阻断 ${r.hard.length} | 提示 ${r.soft.length} | 待补 ${r.need.length} | 未覆盖 ${r.uncovered.length}`,
31
+ ];
32
+ for (const x of r.hard) L.push(`[阻断 ${x.code}] ${x.where} ${x.msg}${x.actual ? `;实际 ${x.actual} → 应为 ${x.expect}` : ''}`);
33
+ for (const x of r.soft) L.push(`[提示 ${x.code}] ${x.where} ${x.msg}${x.actual ? `;实际 ${x.actual} → 应为 ${x.expect}` : ''}`);
34
+ for (const x of r.need) L.push(`[待补] ${x}`);
35
+ for (const x of r.uncovered) L.push(`[未覆盖] ${x}`);
36
+ if (r.sect) L.push(`页面:上${r.sect.marginTopMm ?? '-'} 下${r.sect.marginBottomMm ?? '-'} 左${r.sect.marginLeftMm ?? '-'} 右${r.sect.marginRightMm ?? '-'} mm;纸 ${r.sect.pageWMm ?? '-'}×${r.sect.pageHMm ?? '-'} mm`);
37
+ return L.join('\n');
38
+ }
39
+
40
+ function callTool(name, args) {
41
+ try {
42
+ if (name !== 'check_thesis_format') throw new Error(`未知工具:${name}`);
43
+ if (!args || !args.path) throw new Error('缺少 path');
44
+ const p = String(args.path);
45
+ if (!fs.existsSync(p)) throw new Error(`文件不存在:${p}`);
46
+ if (!/\.docx$/i.test(p)) throw new Error('只支持 .docx(.doc 请先另存为 .docx)');
47
+ const doc = readDocx(p);
48
+ if (!doc.paragraphs.length) throw new Error('文档里没有可读段落');
49
+ const res = check(doc);
50
+ return {
51
+ content: [{ type: 'text', text: brief(res) + '\n\n--- JSON ---\n' + JSON.stringify(res, null, 2) }],
52
+ isError: false,
53
+ };
54
+ } catch (e) {
55
+ return { content: [{ type: 'text', text: `核验失败:${e && e.message ? e.message : String(e)}` }], isError: true };
56
+ }
57
+ }
58
+
59
+ function dispatch(msg) {
60
+ const id = msg && msg.id;
61
+ const method = msg && msg.method;
62
+ if (method === 'initialize') {
63
+ return { jsonrpc: '2.0', id, result: {
64
+ protocolVersion: '2024-11-05',
65
+ capabilities: { tools: {} },
66
+ serverInfo: { name: NAME, version: VERSION },
67
+ } };
68
+ }
69
+ if (method === 'notifications/initialized' || method === 'initialized') return null;
70
+ if (method === 'tools/list') return { jsonrpc: '2.0', id, result: { tools: TOOLS } };
71
+ if (method === 'tools/call') {
72
+ const n = msg.params && msg.params.name;
73
+ const a = msg.params && msg.params.arguments;
74
+ return { jsonrpc: '2.0', id, result: callTool(n, a) };
75
+ }
76
+ if (method === 'ping') return { jsonrpc: '2.0', id, result: {} };
77
+ return { jsonrpc: '2.0', id, error: { code: -32601, message: `Method not found: ${method}` } };
78
+ }
79
+
80
+ const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
81
+ rl.on('line', (line) => {
82
+ const s = String(line).trim();
83
+ if (!s) return;
84
+ let msg;
85
+ try { msg = JSON.parse(s); } catch { return; }
86
+ const out = dispatch(msg);
87
+ if (out) process.stdout.write(JSON.stringify(out) + '\n');
88
+ });
package/lib/io.js ADDED
@@ -0,0 +1,208 @@
1
+ // 零依赖 IO:CSV / XLSX / DOCX(Node 内置 zlib + 手写 ZIP central directory)
2
+ // 不引入任何 npm 依赖;平台 stdio 只认 node,用户机器不保证有 Python。
3
+ import fs from 'node:fs';
4
+ import zlib from 'node:zlib';
5
+
6
+ export function decodeXml(s) {
7
+ return String(s == null ? '' : s)
8
+ .replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"')
9
+ .replace(/&apos;/g, "'").replace(/&#(\d+);/g, (_, n) => String.fromCharCode(+n))
10
+ .replace(/&amp;/g, '&');
11
+ }
12
+
13
+ // ---------- CSV ----------
14
+ export function parseCsv(text) {
15
+ const rows = [];
16
+ let row = [], field = '', quoted = false;
17
+ text = String(text).replace(/^\uFEFF/, '');
18
+ for (let i = 0; i < text.length; i++) {
19
+ const c = text[i];
20
+ if (quoted) {
21
+ if (c === '"') {
22
+ if (text[i + 1] === '"') { field += '"'; i++; }
23
+ else quoted = false;
24
+ } else field += c;
25
+ } else if (c === '"') quoted = true;
26
+ else if (c === ',' || c === '\t') { row.push(field); field = ''; }
27
+ else if (c === '\n') { row.push(field.replace(/\r$/, '')); rows.push(row); row = []; field = ''; }
28
+ else field += c;
29
+ }
30
+ if (field || row.length) { row.push(field); rows.push(row); }
31
+ return rows.filter(r => r.some(x => String(x).trim() !== ''));
32
+ }
33
+
34
+ // ---------- ZIP ----------
35
+ function zipEntries(buf) {
36
+ let eocd = -1;
37
+ for (let i = buf.length - 22; i >= 0; i--) {
38
+ if (buf.readUInt32LE(i) === 0x06054b50) { eocd = i; break; }
39
+ }
40
+ if (eocd < 0) throw new Error('不是有效的 Office 文件:找不到 ZIP 结束记录');
41
+ const count = buf.readUInt16LE(eocd + 10);
42
+ let p = buf.readUInt32LE(eocd + 16);
43
+ const out = {};
44
+ for (let i = 0; i < count; i++) {
45
+ if (p + 46 > buf.length || buf.readUInt32LE(p) !== 0x02014b50) break;
46
+ const method = buf.readUInt16LE(p + 10);
47
+ const csize = buf.readUInt32LE(p + 20);
48
+ const nameLen = buf.readUInt16LE(p + 28);
49
+ const extraLen = buf.readUInt16LE(p + 30);
50
+ const commentLen = buf.readUInt16LE(p + 32);
51
+ const local = buf.readUInt32LE(p + 42);
52
+ const name = buf.toString('utf8', p + 46, p + 46 + nameLen);
53
+ if (local + 30 > buf.length) { p += 46 + nameLen + extraLen + commentLen; continue; }
54
+ const lnLen = buf.readUInt16LE(local + 26);
55
+ const lxLen = buf.readUInt16LE(local + 28);
56
+ const start = local + 30 + lnLen + lxLen;
57
+ const comp = buf.subarray(start, start + csize);
58
+ let data;
59
+ try { data = method === 8 ? zlib.inflateRawSync(comp) : Buffer.from(comp); }
60
+ catch { data = Buffer.from(comp); }
61
+ out[name] = data.toString('utf8');
62
+ p += 46 + nameLen + extraLen + commentLen;
63
+ }
64
+ return out;
65
+ }
66
+
67
+ function colNum(ref) {
68
+ const m = /^([A-Z]+)/.exec(ref || '');
69
+ if (!m) return 0;
70
+ let n = 0;
71
+ for (const ch of m[1]) n = n * 26 + (ch.charCodeAt(0) - 64);
72
+ return n - 1;
73
+ }
74
+
75
+ // ---------- XLSX ----------
76
+ export function readXlsx(path, sheetIndex = 0) {
77
+ const entries = zipEntries(fs.readFileSync(path));
78
+ const shared = [];
79
+ if (entries['xl/sharedStrings.xml']) {
80
+ for (const si of entries['xl/sharedStrings.xml'].match(/<si[\s\S]*?<\/si>/g) || []) {
81
+ shared.push([...si.matchAll(/<t[^>]*>([\s\S]*?)<\/t>/g)].map(x => decodeXml(x[1])).join(''));
82
+ }
83
+ }
84
+ let target = `xl/worksheets/sheet${sheetIndex + 1}.xml`;
85
+ const wb = entries['xl/workbook.xml'];
86
+ const rels = entries['xl/_rels/workbook.xml.rels'];
87
+ if (wb && rels) {
88
+ const sheets = [...wb.matchAll(/<sheet\s([^>]*)\/?>/g)];
89
+ const s = sheets[sheetIndex];
90
+ if (s) {
91
+ const rid = (/r:id="([^"]+)"/.exec(s[1]) || [])[1];
92
+ const rel = rid && [...rels.matchAll(/<Relationship\s([^>]*)\/?>/g)]
93
+ .find(x => (new RegExp(`Id="${rid}"`)).test(x[1]));
94
+ if (rel) {
95
+ const tgt = (/Target="([^"]+)"/.exec(rel[1]) || [])[1];
96
+ if (tgt) target = tgt.startsWith('xl/') ? tgt : 'xl/' + tgt.replace(/^\//, '');
97
+ }
98
+ }
99
+ }
100
+ const xml = entries[target];
101
+ if (!xml) throw new Error(`xlsx 缺少工作表 ${target}`);
102
+ const rows = [];
103
+ for (const rm of xml.matchAll(/<row[^>]*>([\s\S]*?)<\/row>/g)) {
104
+ const cells = {};
105
+ for (const cm of rm[1].matchAll(/<c\s([^>]*)>([\s\S]*?)<\/c>|<c\s([^>]*)\/>/g)) {
106
+ const attrs = cm[1] || cm[3] || '';
107
+ const body = cm[2] || '';
108
+ const ref = (/r="([A-Z]+)\d+"/.exec(attrs) || [])[1];
109
+ const t = (/t="([^"]+)"/.exec(attrs) || [])[1];
110
+ let val = '';
111
+ if (t === 'inlineStr') {
112
+ const im = /<t[^>]*>([\s\S]*?)<\/t>/.exec(body);
113
+ val = im ? decodeXml(im[1]) : '';
114
+ } else {
115
+ const vm = /<v>([\s\S]*?)<\/v>/.exec(body);
116
+ if (vm) val = t === 's' ? (shared[+vm[1]] || '') : decodeXml(vm[1]);
117
+ }
118
+ cells[colNum(ref)] = String(val).trim();
119
+ }
120
+ const keys = Object.keys(cells).map(Number);
121
+ const max = keys.length ? Math.max(...keys) : -1;
122
+ rows.push(max >= 0 ? Array.from({ length: max + 1 }, (_, i) => cells[i] || '') : []);
123
+ }
124
+ return rows;
125
+ }
126
+
127
+ export function sheetNames(path) {
128
+ const entries = zipEntries(fs.readFileSync(path));
129
+ const wb = entries['xl/workbook.xml'] || '';
130
+ return [...wb.matchAll(/<sheet\s[^>]*name="([^"]+)"/g)].map(m => decodeXml(m[1]));
131
+ }
132
+
133
+ // ---------- DOCX ----------
134
+ const TWIP2MM = 25.4 / 1440;
135
+
136
+ export function readDocx(path) {
137
+ const entries = zipEntries(fs.readFileSync(path));
138
+ const raw = entries['word/document.xml'];
139
+ if (!raw) throw new Error('不是有效的 .docx:缺少 word/document.xml');
140
+
141
+ // 样式表:styleId → 显示名
142
+ const styles = {};
143
+ const sx = entries['word/styles.xml'] || '';
144
+ for (const sm of sx.matchAll(/<w:style\s([^>]*)>([\s\S]*?)<\/w:style>/g)) {
145
+ const id = (/w:styleId="([^"]+)"/.exec(sm[1]) || [])[1];
146
+ const nm = (/<w:name\s+w:val="([^"]*)"/.exec(sm[2]) || [])[1];
147
+ if (id) styles[id] = nm || id;
148
+ }
149
+
150
+ // 表格先剥离(表格内段落不参与章节/参考文献判定),只记数量
151
+ const tableCount = (raw.match(/<w:tbl>/g) || []).length;
152
+ const body = raw.replace(/<w:tbl>[\s\S]*?<\/w:tbl>/g, '');
153
+
154
+ const paras = [];
155
+ for (const pm of body.matchAll(/<w:p\b[^>]*>([\s\S]*?)<\/w:p>/g)) {
156
+ const b = pm[1];
157
+ const styleId = (/<w:pStyle\s+w:val="([^"]+)"/.exec(b) || [])[1] || '';
158
+ const numId = (/<w:numId\s+w:val="(\d+)"/.exec(b) || [])[1] || '';
159
+ const ilvl = (/<w:ilvl\s+w:val="(\d+)"/.exec(b) || [])[1] || '';
160
+ const jc = (/<w:jc\s+w:val="([^"]+)"/.exec(b) || [])[1] || '';
161
+ const outline = (/<w:outlineLvl\s+w:val="(\d+)"/.exec(b) || [])[1];
162
+ let text = '';
163
+ for (const tm of b.matchAll(/<w:t(?:\s[^>]*)?>([\s\S]*?)<\/w:t>|<w:tab\/>|<w:br\/>/g)) {
164
+ if (tm[0] === '<w:tab/>') text += '\t';
165
+ else if (tm[0] === '<w:br/>') text += '\n';
166
+ else text += decodeXml(tm[1]);
167
+ }
168
+ if (!text.trim() && !styleId) continue;
169
+ paras.push({
170
+ text: text.replace(/\u00a0/g, ' '),
171
+ style: styleId,
172
+ styleName: styles[styleId] || '',
173
+ numId, ilvl, jc,
174
+ outline: outline === undefined ? null : Number(outline),
175
+ });
176
+ }
177
+
178
+ // 页面设置(取最后一个 sectPr)
179
+ let sect = null;
180
+ const sects = [...raw.matchAll(/<w:sectPr\b[^>]*>([\s\S]*?)<\/w:sectPr>/g)];
181
+ const lastSect = sects.length ? sects[sects.length - 1][1] : '';
182
+ if (lastSect) {
183
+ const mar = (/<w:pgMar\s([^>]*)\/?>/.exec(lastSect) || [])[1] || '';
184
+ const sz = (/<w:pgSz\s([^>]*)\/?>/.exec(lastSect) || [])[1] || '';
185
+ const g = (attr, s) => {
186
+ const m = new RegExp(`w:${attr}="(-?\\d+)"`).exec(s);
187
+ return m ? Number(m[1]) : null;
188
+ };
189
+ sect = {
190
+ marginTopMm: g('top', mar) != null ? +(g('top', mar) * TWIP2MM).toFixed(1) : null,
191
+ marginBottomMm: g('bottom', mar) != null ? +(g('bottom', mar) * TWIP2MM).toFixed(1) : null,
192
+ marginLeftMm: g('left', mar) != null ? +(g('left', mar) * TWIP2MM).toFixed(1) : null,
193
+ marginRightMm: g('right', mar) != null ? +(g('right', mar) * TWIP2MM).toFixed(1) : null,
194
+ pageWMm: g('w', sz) != null ? +(g('w', sz) * TWIP2MM).toFixed(1) : null,
195
+ pageHMm: g('h', sz) != null ? +(g('h', sz) * TWIP2MM).toFixed(1) : null,
196
+ };
197
+ }
198
+
199
+ return { paragraphs: paras, tables: tableCount, sect, styles };
200
+ }
201
+
202
+ export function loadRows(path, sheetIndex = 0) {
203
+ const p = String(path);
204
+ if (/\.csv$/i.test(p)) return { format: 'csv', rows: parseCsv(fs.readFileSync(p, 'utf8')) };
205
+ if (/\.xlsx$/i.test(p)) return { format: 'xlsx', rows: readXlsx(p, sheetIndex) };
206
+ if (/\.txt$/i.test(p)) return { format: 'txt', rows: parseCsv(fs.readFileSync(p, 'utf8')) };
207
+ throw new Error('只支持 .csv / .xlsx / .txt');
208
+ }
package/lib/thesis.js ADDED
@@ -0,0 +1,318 @@
1
+ // 论文格式核验引擎(零依赖)
2
+ // 依据:GB/T 7714—2015《信息与文献 参考文献著录规则》
3
+ // GB/T 7713.1—2006《学位论文编写规则》(现行有效,2022 年修订稿尚未发布)
4
+ // 只读不改文件;每条问题带段落序号、实际值、应为值。
5
+
6
+ export const VERDICT_NOTE = {
7
+ '可交': '未发现硬性问题,可以直接交',
8
+ '先改再交': '有可修的问题,改完再交',
9
+ '交不了': '有硬性问题,按现有内容交不了',
10
+ '待补': '材料不齐,先补齐再核',
11
+ };
12
+
13
+ // 文献类型标识 → 中文名(GB/T 7714—2015 表 1)
14
+ const TYPE_NAME = {
15
+ M: '专著', C: '论文集', N: '报纸', J: '期刊', D: '学位论文',
16
+ R: '报告', S: '标准', P: '专利', G: '汇编', Z: '其他',
17
+ 'EB/OL': '电子文献', 'M/OL': '在线专著', 'J/OL': '在线期刊',
18
+ 'D/OL': '在线学位论文', 'C/OL': '在线论文集', 'DB/OL': '数据库',
19
+ 'CP/DK': '计算机程序', A: '档案',
20
+ };
21
+
22
+ // 正文引文标注:顺序编码制 [1] / [1,2] / [1-3]
23
+ function collectCitations(text) {
24
+ const set = new Set();
25
+ for (const m of text.matchAll(/\[(\d+(?:\s*[-–—,,、]\s*\d+)*)\]/g)) {
26
+ for (const seg of m[1].split(/[,,、]/)) {
27
+ const r = /^\s*(\d+)\s*[-–—]\s*(\d+)\s*$/.exec(seg);
28
+ if (r) {
29
+ const a = +r[1], b = +r[2];
30
+ if (b >= a && b - a < 200) for (let i = a; i <= b; i++) set.add(i);
31
+ } else {
32
+ const n = parseInt(seg, 10);
33
+ if (n > 0) set.add(n);
34
+ }
35
+ }
36
+ }
37
+ return set;
38
+ }
39
+
40
+ // 取作者段:到第一个「. 」为止,跳过英文缩写首字母后的点
41
+ function authorPart(s) {
42
+ let idx = 0;
43
+ for (let guard = 0; guard < 20; guard++) {
44
+ const i = s.indexOf('.', idx);
45
+ if (i < 0) return s;
46
+ const prev = s.slice(Math.max(0, i - 1), i);
47
+ if (/^[A-Z]$/.test(prev)) { idx = i + 1; continue; }
48
+ return s.slice(0, i);
49
+ }
50
+ return s;
51
+ }
52
+
53
+ function countAuthors(seg) {
54
+ return seg.split(/[,,、]/).map(x => x.trim())
55
+ .filter(x => x && !/^(等|et\s*al\.?)$/i.test(x)).length;
56
+ }
57
+
58
+ // 按文献类型校验著录要素
59
+ function checkEntryBody(type, rest) {
60
+ const miss = [];
61
+ if (['M', 'C', 'D', 'R', 'G', 'A', 'Z'].includes(type)) {
62
+ if (!/[::][^,,]+[,,]\s*\d{4}/.test(rest)) miss.push('出版地:出版者,出版年');
63
+ } else if (type === 'J') {
64
+ if (!/\d{4}\s*[,,]?\s*\(\s*\d+\s*\)\s*[::]\s*\d+/.test(rest)) miss.push('年(期):起止页码');
65
+ } else if (type === 'N') {
66
+ if (!/\d{4}[-–—]\d{1,2}[-–—]\d{1,2}/.test(rest)) miss.push('出版日期(版次)');
67
+ } else if (type === 'S') {
68
+ if (!/[A-Z]{1,3}(\/[A-Z])?\s*\d/.test(rest)) miss.push('标准编号');
69
+ } else if (type === 'P') {
70
+ if (!/(专利号|CN|ZL|申请号)/.test(rest)) miss.push('专利号');
71
+ } else if (type === 'EB/OL' || type.endsWith('/OL')) {
72
+ if (!/[((]\s*\d{4}/.test(rest)) miss.push('发布日期');
73
+ if (!/[\[[]\s*\d{4}/.test(rest)) miss.push('引用日期');
74
+ if (!/https?:\/\//.test(rest)) miss.push('获取路径 URL');
75
+ }
76
+ return miss;
77
+ }
78
+
79
+ export function check(doc) {
80
+ const P = doc.paragraphs || [];
81
+ const hard = [], soft = [], uncovered = [], need = [];
82
+ const push = (arr, code, where, msg, actual, expect) =>
83
+ arr.push({ code, where, msg, actual: actual || '', expect: expect || '' });
84
+
85
+ const T = (p) => (p.text || '').trim();
86
+ const allText = P.map(T).join('\n');
87
+
88
+ // ---------- 定位参考文献区 ----------
89
+ const refStart = P.findIndex(p => /^参考文献\s*$/.test(T(p)) || /^参\s*考\s*文\s*献\s*$/.test(T(p)));
90
+ const tailRe = /^(附\s*录|致\s*谢|攻读|作者简介|个人简历|在学期间)/;
91
+ let refEnd = P.length;
92
+ if (refStart >= 0) {
93
+ for (let i = refStart + 1; i < P.length; i++) {
94
+ if (tailRe.test(T(P[i]))) { refEnd = i; break; }
95
+ }
96
+ }
97
+ const refParas = refStart >= 0 ? P.slice(refStart + 1, refEnd) : [];
98
+
99
+ // ---------- 必备要素 ----------
100
+ const hasAbstract = /摘\s*要/.test(allText);
101
+ const hasKeywords = /关\s*键\s*词/.test(allText);
102
+ const hasToc = /目\s*录/.test(allText);
103
+ const hasAck = /致\s*谢/.test(allText);
104
+ if (!hasAbstract) need.push('缺「摘要」');
105
+ if (!hasKeywords) need.push('缺「关键词」');
106
+ if (!hasToc) soft.push({ code: 'NO_TOC', where: '全文', msg: '未找到「目录」', actual: '', expect: '学位论文应有目次页' });
107
+ if (!hasAck) soft.push({ code: 'NO_ACK', where: '全文', msg: '未找到「致谢」', actual: '', expect: '学位论文一般应有致谢' });
108
+ if (refStart < 0) need.push('缺「参考文献」一节');
109
+
110
+ // ---------- 参考文献著录 ----------
111
+ const entries = [];
112
+ refParas.forEach((p, k) => {
113
+ const t = T(p);
114
+ if (!t) return;
115
+ const m = /^[\[[](\d+)[\]]]\s*(.*)$/.exec(t) || /^(\d+)[.、]\s*(.*)$/.exec(t);
116
+ if (m) entries.push({ no: +m[1], body: m[2].trim(), where: `参考文献第${k + 1}段`, raw: t });
117
+ });
118
+
119
+ // 序号连续
120
+ entries.forEach((e, i) => {
121
+ if (e.no !== i + 1) {
122
+ push(hard, 'REF_SEQ', e.where, `参考文献序号不连续:应为 [${i + 1}]`, `[${e.no}]`, `[${i + 1}]`);
123
+ }
124
+ });
125
+
126
+ // 逐条格式
127
+ for (const e of entries) {
128
+ const tm = /[\[[]([A-Z]{1,3}(?:\/[A-Z]{2})?)[\]]]/.exec(e.body);
129
+ if (!tm) {
130
+ push(hard, 'REF_NO_TYPE', e.where, `缺文献类型标识(如 [M]/[J]/[D])`, e.raw.slice(0, 40), '题名后加 [M] 等');
131
+ continue;
132
+ }
133
+ const type = tm[1];
134
+ if (!TYPE_NAME[type]) {
135
+ push(soft, 'REF_TYPE_UNKNOWN', e.where, `文献类型标识 [${type}] 不在 GB/T 7714 表内`, `[${type}]`, 'M/J/D/C/N/S/P/R/EB/OL 等');
136
+ continue;
137
+ }
138
+ const rest = e.body.slice(tm.index + tm[0].length);
139
+ const miss = checkEntryBody(type, rest);
140
+ if (miss.length) {
141
+ push(hard, 'REF_FIELDS', e.where,
142
+ `${TYPE_NAME[type]} [${type}] 缺著录项:${miss.join(' / ')}`, e.raw.slice(0, 60),
143
+ `[序号]主要责任者.题名[${type}].${miss.join(',')}.`);
144
+ }
145
+ // 期号不补 0(GB/T 7714 示例:2015(4) 而非 2015(04))
146
+ if (type === 'J' && /\d{4}\s*\(\s*0\d\s*\)/.test(rest)) {
147
+ push(soft, 'REF_ISSUE_ZERO', e.where, '期刊期号补了前导 0', (/\d{4}\s*\(\s*0\d\s*\)/.exec(rest) || [])[0], '写 2015(4),不写 2015(04)');
148
+ }
149
+ // 作者 >3 应用「等 / et al」
150
+ const ap = authorPart(e.body);
151
+ const n = countAuthors(ap);
152
+ if (n >= 4 && !/等|et\s*al/i.test(ap)) {
153
+ push(hard, 'REF_ETAL', e.where,
154
+ `作者 ${n} 人,著录前 3 位后应加「,等」(英文 et al)`, ap.slice(0, 40), '张三,李四,王五,等.');
155
+ }
156
+ if (n > 3 && /等|et\s*al/i.test(ap) && countAuthors(ap.replace(/[,,]?\s*(等|et\s*al\.?)/i, '')) !== 3) {
157
+ push(soft, 'REF_ETAL_COUNT', e.where, '用「等」时应只列前 3 位作者', ap.slice(0, 40), '列 3 位 + ,等');
158
+ }
159
+ }
160
+
161
+ // ---------- 正文引用 ↔ 文末列表 ----------
162
+ const bodyText = (refStart >= 0 ? P.slice(0, refStart) : P).map(T).join('\n');
163
+ const cited = collectCitations(bodyText);
164
+ const maxNo = entries.length;
165
+ for (const n of [...cited].sort((a, b) => a - b)) {
166
+ if (n > maxNo) {
167
+ push(hard, 'CITE_MISSING', '正文', `正文引用 [${n}],但文末只有 ${maxNo} 条参考文献`, `[${n}]`, '补齐该条或改引文序号');
168
+ }
169
+ }
170
+ const citedSet = new Set(entries.map(e => e.no));
171
+ for (const no of [...citedSet].sort((a, b) => a - b)) {
172
+ if (!cited.has(no)) {
173
+ push(soft, 'REF_UNCITED', `参考文献 [${no}]`, '文末有该条,正文未引用', `[${no}]`, '正文补引或删该条');
174
+ }
175
+ }
176
+
177
+ // ---------- 章节编号 ----------
178
+ const headRe = /^(\d+(?:\.\d+)*)[\s\u3000]+\S/;
179
+ const heads = [];
180
+ P.forEach((p, i) => {
181
+ const t = T(p);
182
+ if (!t || t.length > 60) return;
183
+ // 目录行(带点线引导符)不算正文标题
184
+ if (/[..·…]{3,}/.test(t)) return;
185
+ const m = headRe.exec(t);
186
+ if (!m) return;
187
+ const isHeadingStyle = /heading|标题/i.test(p.styleName || '') || p.outline != null;
188
+ if (!isHeadingStyle && t.length > 30) return;
189
+ heads.push({ idx: i, num: m[1], text: t });
190
+ });
191
+ let counters = []; // counters[level-1] = 该级最近一次编号
192
+ heads.forEach((h, hi) => {
193
+ const parts = h.num.split('.').map(Number);
194
+ const lv = parts.length;
195
+ if (hi === 0) {
196
+ if (parts[0] !== 1) push(hard, 'HEAD_START', `段落${h.idx + 1}`, '第一个章节编号不是 1', h.num, '1');
197
+ counters = [1];
198
+ return;
199
+ }
200
+ if (lv > counters.length + 1) {
201
+ push(hard, 'HEAD_SKIP', `段落${h.idx + 1}`, `章节跳级:上一节为 ${heads[hi - 1].num},本节 ${h.num}`, h.num,
202
+ `最多到 ${heads[hi - 1].num}.1`);
203
+ counters = parts.slice();
204
+ return;
205
+ }
206
+ // 上级编号必须与已记录的上级一致
207
+ let ancestorBad = false;
208
+ for (let i = 0; i < lv - 1; i++) {
209
+ if (parts[i] !== counters[i]) {
210
+ push(hard, 'HEAD_PARENT', `段落${h.idx + 1}`, `上级编号不符:${h.num} 的父级应为 ${counters.slice(0, lv - 1).join('.')}`, h.num, `${counters.slice(0, lv - 1).join('.')}.1`);
211
+ ancestorBad = true;
212
+ break;
213
+ }
214
+ }
215
+ if (!ancestorBad) {
216
+ const exp = (counters[lv - 1] || 0) + 1;
217
+ if (parts[lv - 1] < exp) {
218
+ push(hard, 'HEAD_BACK', `段落${h.idx + 1}`, `编号回落或重号:${heads[hi - 1].num} → ${h.num}`, h.num, `应为 ${parts.slice(0, lv - 1).concat(exp).join('.')}`);
219
+ } else if (parts[lv - 1] > exp) {
220
+ push(soft, 'HEAD_GAP', `段落${h.idx + 1}`, `同级编号不连续:${heads[hi - 1].num} → ${h.num}`, h.num, `应为 ${parts.slice(0, lv - 1).concat(exp).join('.')}`);
221
+ }
222
+ }
223
+ counters = parts.slice();
224
+ });
225
+
226
+ // ---------- 图表编号 ----------
227
+ const figs = [], tabs = [];
228
+ P.forEach((p, i) => {
229
+ const t = T(p);
230
+ const fm = /^图\s*(\d+(?:\s*[-–—.]\s*\d+)?)\s*\S/.exec(t);
231
+ if (fm) figs.push({ idx: i, no: fm[1].replace(/\s/g, '').replace(/[–—.]/g, '-') });
232
+ const tb = /^表\s*(\d+(?:\s*[-–—.]\s*\d+)?)\s*\S/.exec(t);
233
+ if (tb) tabs.push({ idx: i, no: tb[1].replace(/\s/g, '').replace(/[–—.]/g, '-') });
234
+ });
235
+ const seqCheck = (list, label, code) => {
236
+ const seen = new Set();
237
+ list.forEach((x, k) => {
238
+ if (seen.has(x.no)) push(hard, code + '_DUP', `段落${x.idx + 1}`, `${label}编号重复:${label}${x.no}`, `${label}${x.no}`, '改唯一编号');
239
+ seen.add(x.no);
240
+ if (x.no.includes('-')) {
241
+ const [ch, n] = x.no.split('-').map(Number);
242
+ const prevSame = list.slice(0, k).filter(y => y.no.includes('-') && Number(y.no.split('-')[0]) === ch).pop();
243
+ if (prevSame && n !== Number(prevSame.no.split('-')[1]) + 1) {
244
+ push(soft, code + '_GAP', `段落${x.idx + 1}`, `${label}编号不连续:${label}${prevSame.no} → ${label}${x.no}`, `${label}${x.no}`, `${label}${ch}-${Number(prevSame.no.split('-')[1]) + 1}`);
245
+ }
246
+ if (n === 1) {
247
+ const prevOther = list.slice(0, k).filter(y => y.no.includes('-')).pop();
248
+ if (prevOther && Number(prevOther.no.split('-')[0]) > ch) {
249
+ push(soft, code + '_CH', `段落${x.idx + 1}`, `${label}章号倒序:${label}${prevOther.no} → ${label}${x.no}`, `${label}${x.no}`, '按章顺序递增');
250
+ }
251
+ }
252
+ }
253
+ });
254
+ };
255
+ seqCheck(figs, '图', 'FIG');
256
+ seqCheck(tabs, '表', 'TAB');
257
+
258
+ // ---------- 摘要与关键词 ----------
259
+ const absIdx = P.findIndex(p => /^摘\s*要\s*$/.test(T(p)));
260
+ if (absIdx >= 0) {
261
+ let chars = 0;
262
+ for (let i = absIdx + 1; i < P.length; i++) {
263
+ const t = T(P[i]);
264
+ if (/^(关\s*键\s*词|Abstract|ABSTRACT|关\s*键\s*字)/.test(t)) break;
265
+ chars += (t.match(/[\u4e00-\u9fa5]/g) || []).length;
266
+ }
267
+ if (chars > 0 && chars < 200) {
268
+ push(soft, 'ABS_SHORT', '摘要', `中文摘要约 ${chars} 字,偏短`, `${chars} 字`, 'GB/T 7713.1 建议 300–600 字');
269
+ } else if (chars > 1000) {
270
+ push(soft, 'ABS_LONG', '摘要', `中文摘要约 ${chars} 字,偏长`, `${chars} 字`, 'GB/T 7713.1 建议 300–600 字');
271
+ }
272
+ if (chars === 0) uncovered.push('摘要正文未识别到中文字符,字数未核');
273
+ }
274
+ const kwIdx = P.findIndex(p => /^关\s*键\s*词/.test(T(p)));
275
+ if (kwIdx >= 0) {
276
+ const t = T(P[kwIdx]).replace(/^关\s*键\s*词\s*[::]?\s*/, '');
277
+ const kws = t.split(/[;;,,、]/).map(x => x.trim()).filter(Boolean);
278
+ if (kws.length && (kws.length < 3 || kws.length > 8)) {
279
+ push(soft, 'KW_COUNT', `段落${kwIdx + 1}`, `关键词 ${kws.length} 个,超出 3–8 个`, `${kws.length} 个`, '3–8 个');
280
+ }
281
+ }
282
+
283
+ // ---------- 页面设置 ----------
284
+ const s = doc.sect;
285
+ if (s) {
286
+ if (s.marginTopMm != null && s.marginTopMm < 25) push(hard, 'PAGE_TOP', '页面设置', `上边距 ${s.marginTopMm}mm,小于 25mm`, `${s.marginTopMm}mm`, '≥25mm');
287
+ if (s.marginLeftMm != null && s.marginLeftMm < 25) push(hard, 'PAGE_LEFT', '页面设置', `左边距 ${s.marginLeftMm}mm,小于 25mm`, `${s.marginLeftMm}mm`, '≥25mm');
288
+ if (s.marginBottomMm != null && s.marginBottomMm < 20) push(hard, 'PAGE_BOTTOM', '页面设置', `下边距 ${s.marginBottomMm}mm,小于 20mm`, `${s.marginBottomMm}mm`, '≥20mm');
289
+ if (s.marginRightMm != null && s.marginRightMm < 20) push(hard, 'PAGE_RIGHT', '页面设置', `右边距 ${s.marginRightMm}mm,小于 20mm`, `${s.marginRightMm}mm`, '≥20mm');
290
+ if (s.pageWMm && Math.abs(s.pageWMm - 210) > 2) push(soft, 'PAGE_SIZE', '页面设置', `纸宽 ${s.pageWMm}mm,非 A4`, `${s.pageWMm}mm`, '210mm');
291
+ if (s.pageHMm && Math.abs(s.pageHMm - 297) > 2) push(soft, 'PAGE_SIZE', '页面设置', `纸高 ${s.pageHMm}mm,非 A4`, `${s.pageHMm}mm`, '297mm');
292
+ } else {
293
+ uncovered.push('未读到页面设置(sectPr),页边距与纸张未核');
294
+ }
295
+
296
+ // ---------- 结论 ----------
297
+ let verdict;
298
+ if (need.length) verdict = '待补';
299
+ else if (hard.length) verdict = '交不了';
300
+ else if (soft.length) verdict = '先改再交';
301
+ else verdict = '可交';
302
+
303
+ return {
304
+ verdict,
305
+ verdict_note: VERDICT_NOTE[verdict],
306
+ stats: {
307
+ paragraphs: P.length,
308
+ tables: doc.tables || 0,
309
+ headings: heads.length,
310
+ refs: entries.length,
311
+ cited: cited.size,
312
+ figures: figs.length,
313
+ tables_captioned: tabs.length,
314
+ },
315
+ hard, soft, need, uncovered,
316
+ sect: s || null,
317
+ };
318
+ }
package/package.json CHANGED
@@ -1,6 +1,26 @@
1
- {
2
- "name": "thesis-format-check-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
1
+ {
2
+ "name": "thesis-format-check-mcp",
3
+ "version": "1.0.1",
4
+ "description": "GB/T 7714-2015 & GB/T 7713.1-2006 thesis format checker MCP server (stdio, zero dependency)",
5
+ "type": "module",
6
+ "bin": {
7
+ "thesis-format-check-mcp": "index.js"
8
+ },
9
+ "main": "index.js",
10
+ "files": [
11
+ "index.js",
12
+ "lib/"
13
+ ],
14
+ "engines": {
15
+ "node": ">=18.0.0"
16
+ },
17
+ "keywords": [
18
+ "mcp",
19
+ "thesis",
20
+ "gb7714",
21
+ "论文格式",
22
+ "参考文献"
23
+ ],
24
+ "license": "MIT",
25
+ "dependencies": {}
6
26
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.