@mindstone/mcp-server-google-workspace 0.5.13 → 0.5.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -8,7 +8,7 @@ Google Workspace MCP server — Gmail, Calendar, Drive, Docs, Sheets, Slides, Co
8
8
 
9
9
  ## Status
10
10
 
11
- - **Version:** [0.5.13](./CHANGELOG.md) · npm: not yet published
11
+ - **Version:** [0.5.14](./CHANGELOG.md) · npm: not yet published
12
12
  - **Auth:** OAuth (host-orchestrated) ([`GOOGLE_CLIENT_SECRET`](./server.json))
13
13
  - **Tools:** [123](./src/tools/definitions/) (Gmail, Calendar, Drive, Docs, Sheets, Slides, Contacts, Chat, Meet, Tasks, Forms, Comments, Account)
14
14
  - **Surface:** cloud-api
@@ -214,6 +214,10 @@ Known Drive API limitations for shared-drive files (not fixable in this connecto
214
214
  - Files native to a shared drive have no `owners[]` — ownership belongs to the drive itself. Use `lastModifyingUser` and `createdTime` as proxies when attributing files.
215
215
  - The Revisions API does not support shared-drive files, so `list_file_revisions` / `download_file_revision` only work for My Drive files.
216
216
 
217
+ ### Docs formatting
218
+
219
+ `create_workspace_document`, `replace_workspace_document` and `append_to_workspace_document` write markdown as Docs formatting: headings, bulleted and numbered lists (nested by indent), quotes, code, bold, italic, strikethrough and web or mail links. Tables and images stay as their markdown text, and web addresses and file paths are written exactly as given. Each new paragraph starts as plain body text, without the heading, list or character style of the text before it. An append's first line continues the document's last paragraph and keeps its style, unless it is a heading, list item, quote or code, which starts a new paragraph; start the text with a newline to begin a new paragraph. `insert_workspace_document_text` writes plain text.
220
+
217
221
  ### Docs tabs
218
222
 
219
223
  A Google Doc can hold many tabs, nested up to a few levels deep. Every tab has a tab id such as `t.abc123`; `list_workspace_document_tabs` shows the whole tree with each tab's id, parent and position. A Docs link containing `?tab=t.xxxx` points at one tab, and `t.xxxx` is its tab id.
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Turns markdown text into the Google Docs requests that write it with real formatting.
3
+ *
4
+ * The create, append and replace tools take text that models write as markdown. Inserted as it
5
+ * stands, a reader sees "## Plan" and "**due Friday**" in the document. This writes the text
6
+ * without the markers and styles it instead: headings, bulleted and numbered lists (nested by
7
+ * indent), quotes, code, bold, italic, strikethrough and links. Anything else (tables, images)
8
+ * stays as the text it was written as, and so do web addresses and file paths.
9
+ *
10
+ * Index arithmetic is in UTF-16 code units, which is what both JavaScript strings and the Docs
11
+ * API count.
12
+ */
13
+ import type { docs_v1 } from 'googleapis';
14
+ type InlineStyle = 'bold' | 'italic' | 'strike' | 'code' | 'link';
15
+ interface Span {
16
+ start: number;
17
+ end: number;
18
+ style: InlineStyle;
19
+ url?: string;
20
+ }
21
+ interface Inline {
22
+ text: string;
23
+ spans: Span[];
24
+ }
25
+ type ListKind = 'bullet' | 'number';
26
+ interface Paragraph {
27
+ text: string;
28
+ spans: Span[];
29
+ heading?: number;
30
+ list?: {
31
+ kind: ListKind;
32
+ level: number;
33
+ };
34
+ quote?: boolean;
35
+ code?: boolean;
36
+ }
37
+ export interface MarkdownInsertOptions {
38
+ /** Where the text goes: 1 for an empty body, the body's end index for an append. */
39
+ index: number;
40
+ tabId?: string;
41
+ /**
42
+ * The text lands at the end of an existing paragraph (an append). Its first line then
43
+ * continues that paragraph and keeps its style, unless it is a heading, list item, quote or
44
+ * code, which start a paragraph of their own.
45
+ */
46
+ continuesParagraph?: boolean;
47
+ }
48
+ /**
49
+ * The scanning one document may do, shared by every forward search and nested parse in it: a
50
+ * backstop for text built to defeat what `Line` remembers. Past it, the rest of the text is
51
+ * written as it stands, markers included, as it was before markdown was formatted.
52
+ */
53
+ interface Scan {
54
+ steps: number;
55
+ }
56
+ /** Strip inline markdown from one paragraph's text, recording the styles it asked for. */
57
+ export declare function parseInline(source: string, scan?: Scan, depth?: number): Inline;
58
+ /** Split markdown into paragraphs, one per line, with block markers removed. */
59
+ export declare function parseBlocks(markdown: string, scan?: Scan): Paragraph[];
60
+ /**
61
+ * The requests that insert `markdown` at `options.index` and format it. Send them in one
62
+ * batchUpdate, in this order: list bullets go last, from the end backwards, because creating
63
+ * them removes the tabs that carry each item's nesting level and so moves the text after it.
64
+ */
65
+ export declare function markdownToDocsRequests(markdown: string, options: MarkdownInsertOptions): docs_v1.Schema$Request[];
66
+ export {};
67
+ //# sourceMappingURL=markdown.d.ts.map
@@ -0,0 +1,651 @@
1
+ import { ALL_TEXT_KEYS, normalizeInsertText } from './tabs.js';
2
+ import logger from '../../utils/logger.js';
3
+ const MONOSPACE_FONT = 'Courier New';
4
+ const LINK_COLOR = { color: { rgbColor: { red: 0.0667, green: 0.3333, blue: 0.8 } } };
5
+ const QUOTE_INDENT_PT = 36;
6
+ const NO_INDENT = { magnitude: 0, unit: 'PT' };
7
+ // The blanks after a heading or list marker are matched once, never given back: a line whose
8
+ // rest can't match (it holds a line separator) then fails at once rather than after retrying
9
+ // every split of a long run of blanks.
10
+ const HEADING_RE = /^ {0,3}(#{1,6})(?=([ \t]+))\2(.*)$/;
11
+ const EMPTY_HEADING_RE = /^ {0,3}(#{1,6})[ \t]*$/;
12
+ const RULE_RE = /^ {0,3}([-*_])(?:[ \t]*\1){2,}[ \t]*$/;
13
+ const BULLET_RE = /^([ \t]*)[-*+](?=([ \t]+))\2(.*)$/;
14
+ const NUMBER_RE = /^([ \t]*)\d{1,9}[.)](?=([ \t]+))\2(.*)$/;
15
+ const QUOTE_RE = /^ {0,3}>[ \t]?(.*)$/;
16
+ const FENCE_RE = /^ {0,3}(`{3,}|~{3,})/;
17
+ /**
18
+ * A heading's text without its optional closing hashes ("## Plan ##") and trailing blanks. Done
19
+ * by index rather than a regular expression, which would recheck a long run of blanks from each
20
+ * of its characters.
21
+ */
22
+ function headingText(rest) {
23
+ const isBlank = (k) => rest[k] === ' ' || rest[k] === '\t';
24
+ let end = rest.length;
25
+ while (end > 0 && isBlank(end - 1))
26
+ end -= 1;
27
+ let hashes = end;
28
+ while (hashes > 0 && rest[hashes - 1] === '#')
29
+ hashes -= 1;
30
+ if (hashes < end && hashes > 0 && isBlank(hashes - 1)) {
31
+ end = hashes;
32
+ while (end > 0 && isBlank(end - 1))
33
+ end -= 1;
34
+ }
35
+ return rest.slice(0, end);
36
+ }
37
+ function indentWidth(indent) {
38
+ let width = 0;
39
+ for (const ch of indent)
40
+ width += ch === '\t' ? 4 : 1;
41
+ return width;
42
+ }
43
+ function isWordChar(ch) {
44
+ return ch !== undefined && /[\p{L}\p{N}]/u.test(ch);
45
+ }
46
+ function isSpace(ch) {
47
+ if (ch === undefined)
48
+ return true;
49
+ const code = ch.charCodeAt(0);
50
+ // Most characters are plain ASCII, checked here without a regex: space, tab and line ends.
51
+ if (code < 0x80)
52
+ return code === 0x20 || (code >= 0x09 && code <= 0x0d);
53
+ return /\s/.test(ch);
54
+ }
55
+ const SCAN_STEPS_PER_CHAR = 64;
56
+ const SCAN_STEPS_BASE = 2_000_000;
57
+ /** How deep emphasis and links may nest inside each other; deeper markers stay as text. */
58
+ const MAX_NESTING = 16;
59
+ function newScan(length) {
60
+ return { steps: SCAN_STEPS_PER_CHAR * length + SCAN_STEPS_BASE };
61
+ }
62
+ /** Spend `cost` steps; false once the document's scanning is used up. */
63
+ function spend(scan, cost) {
64
+ const before = scan.steps;
65
+ scan.steps -= cost;
66
+ if (before >= 0 && scan.steps < 0) {
67
+ logger.warn('Docs markdown: the text used up its formatting work; the rest is written as plain text');
68
+ }
69
+ return scan.steps >= 0;
70
+ }
71
+ /**
72
+ * End (exclusive) of the run of the character at `i` ("***", "``"). Each position is counted
73
+ * once, so asking from every character of a long run costs no more than the run itself.
74
+ */
75
+ function runEnd(line, i) {
76
+ const { source, runEnds } = line;
77
+ if (runEnds[i] > i)
78
+ return runEnds[i];
79
+ const ch = source[i];
80
+ let end = i;
81
+ while (source[end] === ch && !(runEnds[end] > end))
82
+ end += 1;
83
+ if (source[end] === ch)
84
+ end = runEnds[end];
85
+ spend(line.scan, end - i);
86
+ runEnds.fill(end, i, end);
87
+ return end;
88
+ }
89
+ /** An underscore next to one of these is part of a name or path, not emphasis. */
90
+ function bindsUnderscore(ch) {
91
+ return isWordChar(ch) || ch === '/' || ch === '\\';
92
+ }
93
+ /**
94
+ * A web address, Windows path or network path, which is written exactly as it stands: its
95
+ * underscores, stars and backslashes are part of the address, not markdown. Closing punctuation
96
+ * and markers at its end belong to the sentence around it ("see https://example.com/a.").
97
+ */
98
+ const LITERAL_TOKEN_RE = /(?:[a-z][a-z0-9+.-]*:\/\/|www\.|[a-z]:\\|\\\\[^\s\\])[^\s<>"]*/iy;
99
+ const TOKEN_TRAILING = new Set("*~.,;:!?'".split(''));
100
+ const TOKEN_BOUNDARY_RE = /[\s("'[<*_~]/;
101
+ /** End (exclusive) of the literal token starting at `start`, or -1 when none starts there. */
102
+ function literalTokenEnd(line, start) {
103
+ const { source } = line;
104
+ if (start > 0 && !TOKEN_BOUNDARY_RE.test(source[start - 1]))
105
+ return -1;
106
+ LITERAL_TOKEN_RE.lastIndex = start;
107
+ const match = LITERAL_TOKEN_RE.exec(source);
108
+ if (!match)
109
+ return -1;
110
+ spend(line.scan, match[0].length);
111
+ // Counted once and trimmed by index: a token can be as long as the paragraph.
112
+ let end = start + match[0].length;
113
+ while (end > start && TOKEN_TRAILING.has(source[end - 1]))
114
+ end -= 1;
115
+ let opens = 0;
116
+ let closes = 0;
117
+ for (let k = start; k < end; k++) {
118
+ if (source[k] === '(')
119
+ opens += 1;
120
+ else if (source[k] === ')')
121
+ closes += 1;
122
+ }
123
+ // A closing bracket the token never opened closes the sentence's bracket, not the token.
124
+ while (end > start && source[end - 1] === ')' && opens < closes) {
125
+ end -= 1;
126
+ closes -= 1;
127
+ }
128
+ return end > start ? end : -1;
129
+ }
130
+ const AUTOLINK_RE = /<((?:https?|mailto):[^\s<>]+)>/y;
131
+ /** The `<address>` autolink starting at `start`, if there is one. */
132
+ function autolinkAt(line, start) {
133
+ AUTOLINK_RE.lastIndex = start;
134
+ const match = AUTOLINK_RE.exec(line.source);
135
+ if (match)
136
+ spend(line.scan, match[0].length);
137
+ return match;
138
+ }
139
+ /**
140
+ * End (exclusive) of the inline construct starting at `start` whose own characters are not
141
+ * markdown around it (code, links, images, autolinks, addresses), or -1 when none starts there.
142
+ */
143
+ function constructEnd(line, start) {
144
+ const known = line.constructs[start];
145
+ if (known !== 0)
146
+ return known;
147
+ const end = findConstructEnd(line, start);
148
+ line.constructs[start] = end;
149
+ return end;
150
+ }
151
+ function findConstructEnd(line, start) {
152
+ const { source } = line;
153
+ const ch = source[start];
154
+ if (ch === '`')
155
+ return findCodeClose(line, start);
156
+ if (ch === '[')
157
+ return matchLink(line, start)?.end ?? -1;
158
+ if (ch === '!' && source[start + 1] === '[')
159
+ return matchLink(line, start + 1)?.end ?? -1;
160
+ if (ch === '<') {
161
+ const auto = autolinkAt(line, start);
162
+ if (auto)
163
+ return start + auto[0].length;
164
+ }
165
+ return literalTokenEnd(line, start);
166
+ }
167
+ const ESCAPABLE = new Set('\\`*_{}[]()#+-.!|~>'.split(''));
168
+ /**
169
+ * Find the closing delimiter for an emphasis run opened at `from`. Runs of the same character in
170
+ * between open and close their own nested emphasis ("*a **b** c*"), so they are paired off first;
171
+ * a run that closes more than they opened ends ours ("**a *b***"). A closer must follow a
172
+ * non-space character; an underscore run must not touch a letter, digit or path separator on its
173
+ * outer side, so snake_case_names and /tmp/_archive_/ stay as they are.
174
+ *
175
+ * When the search reaches the end without closing, a run it opened that nothing ever closed
176
+ * can't be closed by a search from any of its characters either, so those runs are recorded in
177
+ * `line.unclosed`.
178
+ */
179
+ function findCloser(line, delim, from) {
180
+ const { source, scan } = line;
181
+ const ch = delim[0];
182
+ const open = line.open;
183
+ let depth = 0;
184
+ let i = from;
185
+ while (i < source.length) {
186
+ if (!spend(scan, 1))
187
+ return -1;
188
+ const c = source[i];
189
+ if (c === '\\') {
190
+ i += 2;
191
+ continue;
192
+ }
193
+ const construct = constructEnd(line, i);
194
+ if (construct !== -1) {
195
+ i = construct;
196
+ continue;
197
+ }
198
+ if (c !== ch) {
199
+ i += 1;
200
+ continue;
201
+ }
202
+ const end = runEnd(line, i);
203
+ const run = end - i;
204
+ const before = source[i - 1];
205
+ const after = source[i + run];
206
+ const canClose = i > from && !isSpace(before) && !(ch === '_' && bindsUnderscore(after));
207
+ const canOpen = !isSpace(after) && !(ch === '_' && i > from && bindsUnderscore(before));
208
+ let left = run;
209
+ if (canClose) {
210
+ while (left > 0 && depth > 0) {
211
+ const top = depth - 1;
212
+ open.touched[top] = true;
213
+ if (open.count[top] > left) {
214
+ open.count[top] -= left;
215
+ left = 0;
216
+ }
217
+ else {
218
+ left -= open.count[top];
219
+ depth -= 1;
220
+ }
221
+ }
222
+ // A run with markers to spare closes ours and leaves the rest as text ("**bold***"),
223
+ // unless it could open emphasis of its own.
224
+ if (depth === 0 && (left === delim.length || (left > delim.length && !canOpen)))
225
+ return i + run - left;
226
+ }
227
+ if (left > 0 && canOpen) {
228
+ open.count[depth] = left;
229
+ open.at[depth] = i;
230
+ open.end[depth] = end;
231
+ open.touched[depth] = false;
232
+ depth += 1;
233
+ }
234
+ i = end;
235
+ }
236
+ // A search from anywhere in such a run would pair off the same runs after it and run out the
237
+ // same way.
238
+ for (let k = 0; k < depth; k++) {
239
+ if (!open.touched[k] && !line.unclosed[open.at[k]])
240
+ line.unclosed.fill(1, open.at[k], open.end[k]);
241
+ }
242
+ return -1;
243
+ }
244
+ /** End (exclusive) of the inline code span opening at `start`, or -1 when it never closes. */
245
+ function findCodeClose(line, start) {
246
+ const { source, scan } = line;
247
+ const run = runEnd(line, start) - start;
248
+ // No closing run of this length after an earlier opener means none after this one either.
249
+ const unclosedFrom = line.codeUnclosedFrom.get(run);
250
+ if (unclosedFrom !== undefined && start >= unclosedFrom)
251
+ return -1;
252
+ const fence = '`'.repeat(run);
253
+ let i = start + run;
254
+ while (i < source.length) {
255
+ const at = source.indexOf(fence, i);
256
+ if (at === -1)
257
+ break;
258
+ if (!spend(scan, at - i + 1))
259
+ return -1;
260
+ const len = runEnd(line, at) - at;
261
+ if (len === run)
262
+ return at + run;
263
+ i = at + len;
264
+ }
265
+ spend(scan, source.length - i + 1);
266
+ line.codeUnclosedFrom.set(run, Math.min(start, unclosedFrom ?? start));
267
+ return -1;
268
+ }
269
+ /** Strip inline markdown from one paragraph's text, recording the styles it asked for. */
270
+ export function parseInline(source, scan = newScan(source.length), depth = 0) {
271
+ const line = {
272
+ source,
273
+ scan,
274
+ depth,
275
+ constructs: new Int32Array(source.length),
276
+ links: new Map(),
277
+ unclosed: new Uint8Array(source.length),
278
+ runEnds: new Int32Array(source.length),
279
+ codeUnclosedFrom: new Map(),
280
+ open: { count: [], at: [], end: [], touched: [] },
281
+ };
282
+ let text = '';
283
+ const spans = [];
284
+ const appendNested = (inner, style, url) => {
285
+ const start = text.length;
286
+ spend(scan, inner.spans.length);
287
+ for (const span of inner.spans) {
288
+ spans.push({ ...span, start: span.start + start, end: span.end + start });
289
+ }
290
+ text += inner.text;
291
+ if (text.length > start)
292
+ spans.push({ start, end: text.length, style, ...(url ? { url } : {}) });
293
+ };
294
+ const nests = depth < MAX_NESTING;
295
+ let i = 0;
296
+ while (i < source.length) {
297
+ if (!spend(scan, 1)) {
298
+ text += source.slice(i);
299
+ break;
300
+ }
301
+ const ch = source[i];
302
+ const literal = literalTokenEnd(line, i);
303
+ if (literal !== -1) {
304
+ text += source.slice(i, literal);
305
+ i = literal;
306
+ continue;
307
+ }
308
+ if (ch === '\\' && ESCAPABLE.has(source[i + 1] ?? '')) {
309
+ text += source[i + 1];
310
+ i += 2;
311
+ continue;
312
+ }
313
+ if (ch === '`') {
314
+ const close = findCodeClose(line, i);
315
+ if (close !== -1) {
316
+ const run = runEnd(line, i) - i;
317
+ let inner = source.slice(i + run, close - run);
318
+ if (inner.length > 2 && inner.startsWith(' ') && inner.endsWith(' '))
319
+ inner = inner.slice(1, -1);
320
+ appendNested({ text: inner, spans: [] }, 'code');
321
+ i = close;
322
+ continue;
323
+ }
324
+ }
325
+ if (ch === '!' && source[i + 1] === '[') {
326
+ // An image can't be placed from here, so it stays as the markdown it was written as.
327
+ const image = matchLink(line, i + 1);
328
+ if (image) {
329
+ text += source.slice(i, image.end);
330
+ i = image.end;
331
+ continue;
332
+ }
333
+ }
334
+ if (ch === '[' && nests) {
335
+ const link = matchLink(line, i);
336
+ // Google refuses a link it can't open, and one refused request fails the whole write, so
337
+ // anything but a web or mail address stays as the text it was written as.
338
+ if (link && /^(?:https?:\/\/|mailto:)/i.test(link.url)) {
339
+ spend(scan, link.label.length);
340
+ appendNested(parseInline(link.label, scan, depth + 1), 'link', link.url);
341
+ i = link.end;
342
+ continue;
343
+ }
344
+ }
345
+ if (ch === '<') {
346
+ const auto = autolinkAt(line, i);
347
+ if (auto) {
348
+ appendNested({ text: auto[1].replace(/^mailto:/, ''), spans: [] }, 'link', auto[1]);
349
+ i += auto[0].length;
350
+ continue;
351
+ }
352
+ }
353
+ if ((ch === '*' || ch === '_' || ch === '~') && line.unclosed[i]) {
354
+ const end = runEnd(line, i);
355
+ text += source.slice(i, end);
356
+ i = end;
357
+ continue;
358
+ }
359
+ if ((ch === '*' || ch === '_' || ch === '~') && nests) {
360
+ const emphasis = matchEmphasis(line, i);
361
+ if (emphasis) {
362
+ spend(scan, emphasis.innerEnd - emphasis.innerStart);
363
+ const inner = parseInline(source.slice(emphasis.innerStart, emphasis.innerEnd), scan, depth + 1);
364
+ if (emphasis.styles.length === 2) {
365
+ const start = text.length;
366
+ appendNested(inner, emphasis.styles[0]);
367
+ if (text.length > start)
368
+ spans.push({ start, end: text.length, style: emphasis.styles[1] });
369
+ }
370
+ else {
371
+ appendNested(inner, emphasis.styles[0]);
372
+ }
373
+ i = emphasis.end;
374
+ continue;
375
+ }
376
+ }
377
+ text += ch;
378
+ i += 1;
379
+ }
380
+ return { text, spans };
381
+ }
382
+ const LINK_DESTINATION_RE = /\(\s*<?([^\s()<>]+(?:\([^\s()]*\)[^\s()<>]*)*)>?(?:\s+"[^"]*")?\s*\)/y;
383
+ /**
384
+ * The link (or image) whose label opens at `start`. A label that reaches the end of the text
385
+ * without closing leaves every bracket still open inside it unclosed too, so those are recorded
386
+ * as having no link.
387
+ */
388
+ function matchLink(line, start) {
389
+ const known = line.links.get(start);
390
+ if (known !== undefined)
391
+ return known;
392
+ const { source, scan } = line;
393
+ const opens = [];
394
+ let i = start;
395
+ for (; i < source.length; i++) {
396
+ if (!spend(scan, 1))
397
+ return null;
398
+ if (source[i] === '\\') {
399
+ i += 1;
400
+ continue;
401
+ }
402
+ if (source[i] === '[')
403
+ opens.push(i);
404
+ if (source[i] === ']') {
405
+ opens.pop();
406
+ if (opens.length === 0)
407
+ break;
408
+ }
409
+ }
410
+ if (i >= source.length) {
411
+ for (const at of opens)
412
+ line.links.set(at, null);
413
+ return null;
414
+ }
415
+ let link = null;
416
+ if (source[i + 1] === '(') {
417
+ LINK_DESTINATION_RE.lastIndex = i + 1;
418
+ const rest = LINK_DESTINATION_RE.exec(source);
419
+ if (rest) {
420
+ spend(scan, rest[0].length);
421
+ link = { label: source.slice(start + 1, i), url: rest[1], end: i + 1 + rest[0].length };
422
+ }
423
+ }
424
+ line.links.set(start, link);
425
+ return link;
426
+ }
427
+ function matchEmphasis(line, start) {
428
+ const { source } = line;
429
+ const ch = source[start];
430
+ const run = runEnd(line, start) - start;
431
+ if (ch === '_' && bindsUnderscore(source[start - 1]))
432
+ return null;
433
+ const candidates = ch === '~'
434
+ ? [{ delim: '~~', styles: ['strike'] }]
435
+ : [
436
+ { delim: ch.repeat(3), styles: ['bold', 'italic'] },
437
+ { delim: ch.repeat(2), styles: ['bold'] },
438
+ { delim: ch, styles: ['italic'] },
439
+ ];
440
+ for (const { delim, styles } of candidates) {
441
+ if (delim.length > run)
442
+ continue;
443
+ const innerStart = start + delim.length;
444
+ if (isSpace(source[innerStart]))
445
+ continue;
446
+ const close = findCloser(line, delim, innerStart);
447
+ if (close === -1)
448
+ continue;
449
+ return { innerStart, innerEnd: close, end: close + delim.length, styles };
450
+ }
451
+ return null;
452
+ }
453
+ /** Split markdown into paragraphs, one per line, with block markers removed. */
454
+ export function parseBlocks(markdown, scan = newScan(markdown.length)) {
455
+ const lines = markdown.replace(/\r\n?/g, '\n').split('\n');
456
+ const paragraphs = [];
457
+ let fence = null;
458
+ // Indent widths of the open list levels, outermost first.
459
+ let listIndents = [];
460
+ for (const line of lines) {
461
+ if (fence !== null) {
462
+ const close = FENCE_RE.exec(line);
463
+ if (close && close[1][0] === fence[0] && close[1].length >= fence.length && line.trim() === close[1]) {
464
+ fence = null;
465
+ continue;
466
+ }
467
+ paragraphs.push({ text: line, spans: line ? [{ start: 0, end: line.length, style: 'code' }] : [], code: true });
468
+ continue;
469
+ }
470
+ const open = FENCE_RE.exec(line);
471
+ if (open) {
472
+ fence = open[1];
473
+ listIndents = [];
474
+ continue;
475
+ }
476
+ const list = BULLET_RE.exec(line) ?? NUMBER_RE.exec(line);
477
+ if (list && !RULE_RE.test(line)) {
478
+ const width = indentWidth(list[1]);
479
+ while (listIndents.length > 0 && width < listIndents[listIndents.length - 1])
480
+ listIndents.pop();
481
+ if (listIndents.length === 0 || width > listIndents[listIndents.length - 1])
482
+ listIndents.push(width);
483
+ const kind = BULLET_RE.test(line) ? 'bullet' : 'number';
484
+ paragraphs.push({ ...parseInline(list[3], scan), list: { kind, level: listIndents.length - 1 } });
485
+ continue;
486
+ }
487
+ listIndents = [];
488
+ if (RULE_RE.test(line)) {
489
+ paragraphs.push({ text: '', spans: [] });
490
+ continue;
491
+ }
492
+ const heading = HEADING_RE.exec(line);
493
+ if (heading) {
494
+ paragraphs.push({ ...parseInline(headingText(heading[3]), scan), heading: heading[1].length });
495
+ continue;
496
+ }
497
+ const emptyHeading = EMPTY_HEADING_RE.exec(line);
498
+ if (emptyHeading) {
499
+ paragraphs.push({ text: '', spans: [], heading: emptyHeading[1].length });
500
+ continue;
501
+ }
502
+ const quote = QUOTE_RE.exec(line);
503
+ if (quote) {
504
+ paragraphs.push({ ...parseInline(quote[1], scan), quote: true });
505
+ continue;
506
+ }
507
+ paragraphs.push(parseInline(line, scan));
508
+ }
509
+ return paragraphs;
510
+ }
511
+ function isBlock(paragraph) {
512
+ return paragraph.heading !== undefined || paragraph.list !== undefined || !!paragraph.quote || !!paragraph.code;
513
+ }
514
+ function textStyleFor(span) {
515
+ switch (span.style) {
516
+ case 'bold':
517
+ return { textStyle: { bold: true }, fields: 'bold' };
518
+ case 'italic':
519
+ return { textStyle: { italic: true }, fields: 'italic' };
520
+ case 'strike':
521
+ return { textStyle: { strikethrough: true }, fields: 'strikethrough' };
522
+ case 'code':
523
+ return { textStyle: { weightedFontFamily: { fontFamily: MONOSPACE_FONT } }, fields: 'weightedFontFamily' };
524
+ case 'link':
525
+ return {
526
+ textStyle: { link: { url: span.url }, underline: true, foregroundColor: LINK_COLOR },
527
+ fields: 'link,underline,foregroundColor',
528
+ };
529
+ }
530
+ }
531
+ /**
532
+ * The requests that insert `markdown` at `options.index` and format it. Send them in one
533
+ * batchUpdate, in this order: list bullets go last, from the end backwards, because creating
534
+ * them removes the tabs that carry each item's nesting level and so moves the text after it.
535
+ */
536
+ export function markdownToDocsRequests(markdown, options) {
537
+ // Offsets are counted on the text as Docs stores it, without the characters it strips.
538
+ const paragraphs = parseBlocks(normalizeInsertText(markdown).text);
539
+ if (options.continuesParagraph && paragraphs.length > 0 && isBlock(paragraphs[0])) {
540
+ paragraphs.unshift({ text: '', spans: [] });
541
+ }
542
+ const tab = options.tabId !== undefined ? { tabId: options.tabId } : {};
543
+ const range = (startIndex, endIndex) => ({ startIndex, endIndex, ...tab });
544
+ let text = '';
545
+ const placed = [];
546
+ paragraphs.forEach((paragraph, n) => {
547
+ if (n > 0)
548
+ text += '\n';
549
+ const start = text.length;
550
+ if (paragraph.list)
551
+ text += '\t'.repeat(paragraph.list.level);
552
+ const textStart = text.length;
553
+ text += paragraph.text;
554
+ placed.push({ paragraph, start, textStart, end: text.length });
555
+ });
556
+ if (text.length === 0)
557
+ return [];
558
+ const base = options.index;
559
+ const requests = [
560
+ { insertText: { location: { index: base, ...tab }, text } },
561
+ // The inserted text must not take on the style of the text it lands next to.
562
+ { updateTextStyle: { range: range(base, base + text.length), textStyle: {}, fields: ALL_TEXT_KEYS } },
563
+ ];
564
+ // The first line of an append continues the paragraph it lands in and keeps that
565
+ // paragraph's style. The line after a trailing newline is the paragraph that was already
566
+ // there, so it is left alone too.
567
+ const own = placed.filter((entry, n) => {
568
+ if (n === 0 && options.continuesParagraph)
569
+ return false;
570
+ if (n === placed.length - 1 && n > 0 && entry.end === entry.start && text.endsWith('\n'))
571
+ return false;
572
+ return true;
573
+ });
574
+ // New paragraphs copy the style and list of the one they split from (a heading, a bullet), so
575
+ // they start from plain body text; the markdown's own headings, quotes and lists follow.
576
+ if (own.length > 0) {
577
+ const first = own[0].start;
578
+ const last = own[own.length - 1].end;
579
+ const ownRange = range(base + first, base + Math.max(last, first + 1));
580
+ requests.push({ deleteParagraphBullets: { range: ownRange } }, {
581
+ updateParagraphStyle: {
582
+ range: ownRange,
583
+ paragraphStyle: { namedStyleType: 'NORMAL_TEXT', indentStart: NO_INDENT, indentFirstLine: NO_INDENT },
584
+ fields: 'namedStyleType,indentStart,indentFirstLine',
585
+ },
586
+ });
587
+ }
588
+ for (const entry of own) {
589
+ const { paragraph } = entry;
590
+ const paragraphRange = range(base + entry.start, base + entry.start + 1);
591
+ if (paragraph.heading !== undefined) {
592
+ requests.push({
593
+ updateParagraphStyle: {
594
+ range: paragraphRange,
595
+ paragraphStyle: { namedStyleType: `HEADING_${paragraph.heading}` },
596
+ fields: 'namedStyleType',
597
+ },
598
+ });
599
+ }
600
+ else if (paragraph.quote) {
601
+ requests.push({
602
+ updateParagraphStyle: {
603
+ range: paragraphRange,
604
+ paragraphStyle: { indentStart: { magnitude: QUOTE_INDENT_PT, unit: 'PT' } },
605
+ fields: 'indentStart',
606
+ },
607
+ });
608
+ }
609
+ }
610
+ for (const entry of placed) {
611
+ for (const span of entry.paragraph.spans) {
612
+ if (span.end <= span.start)
613
+ continue;
614
+ requests.push({
615
+ updateTextStyle: {
616
+ range: range(base + entry.textStart + span.start, base + entry.textStart + span.end),
617
+ ...textStyleFor(span),
618
+ },
619
+ });
620
+ }
621
+ }
622
+ // Consecutive list items form one list, and the outermost item's kind picks its glyphs; a
623
+ // top-level item of the other kind starts a new list.
624
+ const lists = [];
625
+ let current = null;
626
+ for (const entry of own) {
627
+ const list = entry.paragraph.list;
628
+ if (!list) {
629
+ current = null;
630
+ continue;
631
+ }
632
+ const switchesKind = list.level === 0 && current !== null && current.kind !== list.kind;
633
+ if (current && current.end === entry.start - 1 && !switchesKind) {
634
+ current.end = entry.end;
635
+ }
636
+ else {
637
+ current = { start: entry.start, end: entry.end, kind: list.kind };
638
+ lists.push(current);
639
+ }
640
+ }
641
+ for (const list of lists.reverse()) {
642
+ requests.push({
643
+ createParagraphBullets: {
644
+ range: range(base + list.start, base + Math.max(list.end, list.start + 1)),
645
+ bulletPreset: list.kind === 'number' ? 'NUMBERED_DECIMAL_ALPHA_ROMAN' : 'BULLET_DISC_CIRCLE_SQUARE',
646
+ },
647
+ });
648
+ }
649
+ return requests;
650
+ }
651
+ //# sourceMappingURL=markdown.js.map
@@ -6,6 +6,7 @@ import { DOCS_SCOPES } from './scopes.js';
6
6
  import { describeApiError, describeApiErrorUntrusted, extractHttpStatus, failedResult, isAuthHandoffError, isPassthroughGoogleError, withCause } from '../../utils/apiError.js';
7
7
  import { markMayHaveWritten, preserveGoogleRetryDecision } from '../../utils/google-retry.js';
8
8
  import { wrapUntrustedJsonValues } from '../../utils/untrusted-content.js';
9
+ import { markdownToDocsRequests } from './markdown.js';
9
10
  import { ALL_TEXT_KEYS, DocsInputError, quoteTabId, TAB_READ_TEXT_OPTIONS, TAB_TREE_FIELDS, TRUNCATION_MARKER, assertUniqueTitle, buildAllTabsText, bodyEndIndex, countWords, descendantsOf, extractBodyText, findAnchor, flatParagraphs, flattenTabs, nextParagraphInContainer, normalizeInsertText, paragraphSearchText, requireTabs, resolveTab, siblingsOf, } from './tabs.js';
10
11
  const DEFAULT_MAX_CHARS = 50000;
11
12
  /** Cap on `read_workspace_document` with `tab_id` + `return_json` (enveloped size). */
@@ -242,20 +243,12 @@ export class DocsService extends BaseGoogleService {
242
243
  error: 'Failed to create document - no documentId returned',
243
244
  };
244
245
  }
245
- // Add initial content if provided
246
- if (options.content) {
246
+ // Add initial content if provided, its markdown written as formatting
247
+ const contentRequests = options.content ? markdownToDocsRequests(options.content, { index: 1 }) : [];
248
+ if (contentRequests.length > 0) {
247
249
  await client.documents.batchUpdate({
248
250
  documentId,
249
- requestBody: {
250
- requests: [
251
- {
252
- insertText: {
253
- location: { index: 1 },
254
- text: options.content,
255
- },
256
- },
257
- ],
258
- },
251
+ requestBody: { requests: contentRequests },
259
252
  });
260
253
  }
261
254
  const result = {
@@ -294,19 +287,14 @@ export class DocsService extends BaseGoogleService {
294
287
  const { doc, flat } = await this.readAllTabs(client, options.documentId);
295
288
  const tab = resolveTab(flat, options.tabId, { allowDefault: true });
296
289
  const endIndex = bodyEndIndex(tab.tab.documentTab?.body);
297
- await client.documents.batchUpdate({
298
- documentId: options.documentId,
299
- requestBody: {
300
- requests: [
301
- {
302
- insertText: {
303
- location: { index: endIndex, tabId: tab.tabId },
304
- text: options.text,
305
- },
306
- },
307
- ],
308
- },
290
+ const requests = markdownToDocsRequests(options.text, {
291
+ index: endIndex,
292
+ tabId: tab.tabId,
293
+ continuesParagraph: true,
309
294
  });
295
+ if (requests.length > 0) {
296
+ await client.documents.batchUpdate({ documentId: options.documentId, requestBody: { requests } });
297
+ }
310
298
  const result = {
311
299
  title: doc.title || 'Untitled',
312
300
  documentId: options.documentId,
@@ -320,20 +308,11 @@ export class DocsService extends BaseGoogleService {
320
308
  documentId: options.documentId,
321
309
  });
322
310
  const endIndex = this.getDocumentEndIndex(docResponse.data);
323
- // Append text at the end
324
- await client.documents.batchUpdate({
325
- documentId: options.documentId,
326
- requestBody: {
327
- requests: [
328
- {
329
- insertText: {
330
- location: { index: endIndex },
331
- text: options.text,
332
- },
333
- },
334
- ],
335
- },
336
- });
311
+ // Append text at the end, its markdown written as formatting
312
+ const requests = markdownToDocsRequests(options.text, { index: endIndex, continuesParagraph: true });
313
+ if (requests.length > 0) {
314
+ await client.documents.batchUpdate({ documentId: options.documentId, requestBody: { requests } });
315
+ }
337
316
  const result = {
338
317
  title: docResponse.data.title || 'Untitled',
339
318
  documentId: options.documentId,
@@ -372,13 +351,8 @@ export class DocsService extends BaseGoogleService {
372
351
  },
373
352
  });
374
353
  }
375
- // Insert new content at start
376
- requests.push({
377
- insertText: {
378
- location: { index: 1, ...(tabId !== undefined ? { tabId } : {}) },
379
- text: content,
380
- },
381
- });
354
+ // Insert the new content at the start, its markdown written as formatting
355
+ requests.push(...markdownToDocsRequests(content, { index: 1, tabId }));
382
356
  return requests;
383
357
  }
384
358
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mindstone/mcp-server-google-workspace",
3
- "version": "0.5.13",
3
+ "version": "0.5.14",
4
4
  "mcpName": "io.github.mindstone/mcp-server-google-workspace",
5
5
  "description": "Google Workspace MCP server for Gmail, Calendar, Drive, Docs, Sheets, Slides, Contacts, Tasks, and Forms",
6
6
  "license": "FSL-1.1-MIT",