@mcp-z/mcp-sheets 1.2.2 → 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/README.md +5 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/mcp/prompts/a1-notation.d.cts +2 -3
- package/dist/cjs/mcp/prompts/a1-notation.d.ts +2 -3
- package/dist/cjs/mcp/prompts/a1-notation.js.map +1 -1
- package/dist/cjs/mcp/resources/spreadsheet.js +2 -2
- package/dist/cjs/mcp/resources/spreadsheet.js.map +1 -1
- package/dist/cjs/mcp/tools/cells-format.d.cts +1 -1
- package/dist/cjs/mcp/tools/cells-format.d.ts +1 -1
- package/dist/cjs/mcp/tools/cells-format.js +3 -3
- package/dist/cjs/mcp/tools/cells-format.js.map +1 -1
- package/dist/cjs/mcp/tools/chart-create.d.cts +1 -1
- package/dist/cjs/mcp/tools/chart-create.d.ts +1 -1
- package/dist/cjs/mcp/tools/chart-create.js +7 -7
- package/dist/cjs/mcp/tools/chart-create.js.map +1 -1
- package/dist/cjs/mcp/tools/columns-get.d.cts +1 -1
- package/dist/cjs/mcp/tools/columns-get.d.ts +1 -1
- package/dist/cjs/mcp/tools/columns-get.js +3 -3
- package/dist/cjs/mcp/tools/columns-get.js.map +1 -1
- package/dist/cjs/mcp/tools/columns-update.d.cts +1 -1
- package/dist/cjs/mcp/tools/columns-update.d.ts +1 -1
- package/dist/cjs/mcp/tools/columns-update.js +4 -4
- package/dist/cjs/mcp/tools/columns-update.js.map +1 -1
- package/dist/cjs/mcp/tools/csv-get-columns.d.cts +1 -1
- package/dist/cjs/mcp/tools/csv-get-columns.d.ts +1 -1
- package/dist/cjs/mcp/tools/csv-get-columns.js +2 -2
- package/dist/cjs/mcp/tools/csv-get-columns.js.map +1 -1
- package/dist/cjs/mcp/tools/dimensions-batch-update.d.cts +1 -1
- package/dist/cjs/mcp/tools/dimensions-batch-update.d.ts +1 -1
- package/dist/cjs/mcp/tools/dimensions-batch-update.js +8 -8
- package/dist/cjs/mcp/tools/dimensions-batch-update.js.map +1 -1
- package/dist/cjs/mcp/tools/dimensions-move.d.cts +1 -1
- package/dist/cjs/mcp/tools/dimensions-move.d.ts +1 -1
- package/dist/cjs/mcp/tools/dimensions-move.js +6 -6
- package/dist/cjs/mcp/tools/dimensions-move.js.map +1 -1
- package/dist/cjs/mcp/tools/rows-append.d.cts +1 -1
- package/dist/cjs/mcp/tools/rows-append.d.ts +1 -1
- package/dist/cjs/mcp/tools/rows-append.js +3 -3
- package/dist/cjs/mcp/tools/rows-append.js.map +1 -1
- package/dist/cjs/mcp/tools/rows-csv-append.d.cts +1 -1
- package/dist/cjs/mcp/tools/rows-csv-append.d.ts +1 -1
- package/dist/cjs/mcp/tools/rows-csv-append.js +7 -7
- package/dist/cjs/mcp/tools/rows-csv-append.js.map +1 -1
- package/dist/cjs/mcp/tools/rows-get.d.cts +1 -1
- package/dist/cjs/mcp/tools/rows-get.d.ts +1 -1
- package/dist/cjs/mcp/tools/rows-get.js +4 -4
- package/dist/cjs/mcp/tools/rows-get.js.map +1 -1
- package/dist/cjs/mcp/tools/sheet-copy-to.d.cts +1 -1
- package/dist/cjs/mcp/tools/sheet-copy-to.d.ts +1 -1
- package/dist/cjs/mcp/tools/sheet-copy-to.js +4 -4
- package/dist/cjs/mcp/tools/sheet-copy-to.js.map +1 -1
- package/dist/cjs/mcp/tools/sheet-copy.d.cts +1 -1
- package/dist/cjs/mcp/tools/sheet-copy.d.ts +1 -1
- package/dist/cjs/mcp/tools/sheet-copy.js +4 -4
- package/dist/cjs/mcp/tools/sheet-copy.js.map +1 -1
- package/dist/cjs/mcp/tools/sheet-create.d.cts +1 -1
- package/dist/cjs/mcp/tools/sheet-create.d.ts +1 -1
- package/dist/cjs/mcp/tools/sheet-create.js +3 -3
- package/dist/cjs/mcp/tools/sheet-create.js.map +1 -1
- package/dist/cjs/mcp/tools/sheet-delete.d.cts +1 -1
- package/dist/cjs/mcp/tools/sheet-delete.d.ts +1 -1
- package/dist/cjs/mcp/tools/sheet-delete.js +2 -2
- package/dist/cjs/mcp/tools/sheet-delete.js.map +1 -1
- package/dist/cjs/mcp/tools/sheet-find.d.cts +1 -1
- package/dist/cjs/mcp/tools/sheet-find.d.ts +1 -1
- package/dist/cjs/mcp/tools/sheet-find.js +3 -3
- package/dist/cjs/mcp/tools/sheet-find.js.map +1 -1
- package/dist/cjs/mcp/tools/sheet-rename.d.cts +1 -1
- package/dist/cjs/mcp/tools/sheet-rename.d.ts +1 -1
- package/dist/cjs/mcp/tools/sheet-rename.js +4 -4
- package/dist/cjs/mcp/tools/sheet-rename.js.map +1 -1
- package/dist/cjs/mcp/tools/spreadsheet-copy.d.cts +1 -1
- package/dist/cjs/mcp/tools/spreadsheet-copy.d.ts +1 -1
- package/dist/cjs/mcp/tools/spreadsheet-copy.js +2 -2
- package/dist/cjs/mcp/tools/spreadsheet-copy.js.map +1 -1
- package/dist/cjs/mcp/tools/spreadsheet-create.d.cts +1 -1
- package/dist/cjs/mcp/tools/spreadsheet-create.d.ts +1 -1
- package/dist/cjs/mcp/tools/spreadsheet-create.js +3 -3
- package/dist/cjs/mcp/tools/spreadsheet-create.js.map +1 -1
- package/dist/cjs/mcp/tools/spreadsheet-find.d.cts +1 -1
- package/dist/cjs/mcp/tools/spreadsheet-find.d.ts +1 -1
- package/dist/cjs/mcp/tools/spreadsheet-find.js +2 -2
- package/dist/cjs/mcp/tools/spreadsheet-find.js.map +1 -1
- package/dist/cjs/mcp/tools/spreadsheet-rename.d.cts +1 -1
- package/dist/cjs/mcp/tools/spreadsheet-rename.d.ts +1 -1
- package/dist/cjs/mcp/tools/spreadsheet-rename.js +2 -2
- package/dist/cjs/mcp/tools/spreadsheet-rename.js.map +1 -1
- package/dist/cjs/mcp/tools/validation-set.d.cts +1 -1
- package/dist/cjs/mcp/tools/validation-set.d.ts +1 -1
- package/dist/cjs/mcp/tools/validation-set.js +4 -4
- package/dist/cjs/mcp/tools/validation-set.js.map +1 -1
- package/dist/cjs/mcp/tools/values-batch-update.d.cts +1 -1
- package/dist/cjs/mcp/tools/values-batch-update.d.ts +1 -1
- package/dist/cjs/mcp/tools/values-batch-update.js +5 -5
- package/dist/cjs/mcp/tools/values-batch-update.js.map +1 -1
- package/dist/cjs/mcp/tools/values-clear.d.cts +1 -1
- package/dist/cjs/mcp/tools/values-clear.d.ts +1 -1
- package/dist/cjs/mcp/tools/values-clear.js +3 -3
- package/dist/cjs/mcp/tools/values-clear.js.map +1 -1
- package/dist/cjs/mcp/tools/values-csv-update.d.cts +1 -1
- package/dist/cjs/mcp/tools/values-csv-update.d.ts +1 -1
- package/dist/cjs/mcp/tools/values-csv-update.js +4 -4
- package/dist/cjs/mcp/tools/values-csv-update.js.map +1 -1
- package/dist/cjs/mcp/tools/values-markdown-update.d.cts +1 -1
- package/dist/cjs/mcp/tools/values-markdown-update.d.ts +1 -1
- package/dist/cjs/mcp/tools/values-markdown-update.js +5 -5
- package/dist/cjs/mcp/tools/values-markdown-update.js.map +1 -1
- package/dist/cjs/mcp/tools/values-replace.d.cts +1 -1
- package/dist/cjs/mcp/tools/values-replace.d.ts +1 -1
- package/dist/cjs/mcp/tools/values-replace.js +5 -5
- package/dist/cjs/mcp/tools/values-replace.js.map +1 -1
- package/dist/cjs/mcp/tools/values-search.d.cts +1 -1
- package/dist/cjs/mcp/tools/values-search.d.ts +1 -1
- package/dist/cjs/mcp/tools/values-search.js +3 -3
- package/dist/cjs/mcp/tools/values-search.js.map +1 -1
- package/dist/cjs/setup/http.d.cts +1 -1
- package/dist/cjs/setup/http.d.ts +1 -1
- package/dist/cjs/setup/http.js +23 -13
- package/dist/cjs/setup/http.js.map +1 -1
- package/dist/cjs/setup/stdio.d.cts +1 -1
- package/dist/cjs/setup/stdio.d.ts +1 -1
- package/dist/cjs/setup/stdio.js +1 -2
- package/dist/cjs/setup/stdio.js.map +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/mcp/prompts/a1-notation.d.ts +2 -3
- package/dist/esm/mcp/prompts/a1-notation.js.map +1 -1
- package/dist/esm/mcp/resources/spreadsheet.js +1 -1
- package/dist/esm/mcp/resources/spreadsheet.js.map +1 -1
- package/dist/esm/mcp/tools/cells-format.d.ts +1 -1
- package/dist/esm/mcp/tools/cells-format.js +3 -3
- package/dist/esm/mcp/tools/cells-format.js.map +1 -1
- package/dist/esm/mcp/tools/chart-create.d.ts +1 -1
- package/dist/esm/mcp/tools/chart-create.js +7 -7
- package/dist/esm/mcp/tools/chart-create.js.map +1 -1
- package/dist/esm/mcp/tools/columns-get.d.ts +1 -1
- package/dist/esm/mcp/tools/columns-get.js +3 -3
- package/dist/esm/mcp/tools/columns-get.js.map +1 -1
- package/dist/esm/mcp/tools/columns-update.d.ts +1 -1
- package/dist/esm/mcp/tools/columns-update.js +4 -4
- package/dist/esm/mcp/tools/columns-update.js.map +1 -1
- package/dist/esm/mcp/tools/csv-get-columns.d.ts +1 -1
- package/dist/esm/mcp/tools/csv-get-columns.js +2 -2
- package/dist/esm/mcp/tools/csv-get-columns.js.map +1 -1
- package/dist/esm/mcp/tools/dimensions-batch-update.d.ts +1 -1
- package/dist/esm/mcp/tools/dimensions-batch-update.js +8 -8
- package/dist/esm/mcp/tools/dimensions-batch-update.js.map +1 -1
- package/dist/esm/mcp/tools/dimensions-move.d.ts +1 -1
- package/dist/esm/mcp/tools/dimensions-move.js +6 -6
- package/dist/esm/mcp/tools/dimensions-move.js.map +1 -1
- package/dist/esm/mcp/tools/rows-append.d.ts +1 -1
- package/dist/esm/mcp/tools/rows-append.js +3 -3
- package/dist/esm/mcp/tools/rows-append.js.map +1 -1
- package/dist/esm/mcp/tools/rows-csv-append.d.ts +1 -1
- package/dist/esm/mcp/tools/rows-csv-append.js +7 -7
- package/dist/esm/mcp/tools/rows-csv-append.js.map +1 -1
- package/dist/esm/mcp/tools/rows-get.d.ts +1 -1
- package/dist/esm/mcp/tools/rows-get.js +4 -4
- package/dist/esm/mcp/tools/rows-get.js.map +1 -1
- package/dist/esm/mcp/tools/sheet-copy-to.d.ts +1 -1
- package/dist/esm/mcp/tools/sheet-copy-to.js +4 -4
- package/dist/esm/mcp/tools/sheet-copy-to.js.map +1 -1
- package/dist/esm/mcp/tools/sheet-copy.d.ts +1 -1
- package/dist/esm/mcp/tools/sheet-copy.js +4 -4
- package/dist/esm/mcp/tools/sheet-copy.js.map +1 -1
- package/dist/esm/mcp/tools/sheet-create.d.ts +1 -1
- package/dist/esm/mcp/tools/sheet-create.js +3 -3
- package/dist/esm/mcp/tools/sheet-create.js.map +1 -1
- package/dist/esm/mcp/tools/sheet-delete.d.ts +1 -1
- package/dist/esm/mcp/tools/sheet-delete.js +2 -2
- package/dist/esm/mcp/tools/sheet-delete.js.map +1 -1
- package/dist/esm/mcp/tools/sheet-find.d.ts +1 -1
- package/dist/esm/mcp/tools/sheet-find.js +3 -3
- package/dist/esm/mcp/tools/sheet-find.js.map +1 -1
- package/dist/esm/mcp/tools/sheet-rename.d.ts +1 -1
- package/dist/esm/mcp/tools/sheet-rename.js +4 -4
- package/dist/esm/mcp/tools/sheet-rename.js.map +1 -1
- package/dist/esm/mcp/tools/spreadsheet-copy.d.ts +1 -1
- package/dist/esm/mcp/tools/spreadsheet-copy.js +2 -2
- package/dist/esm/mcp/tools/spreadsheet-copy.js.map +1 -1
- package/dist/esm/mcp/tools/spreadsheet-create.d.ts +1 -1
- package/dist/esm/mcp/tools/spreadsheet-create.js +3 -3
- package/dist/esm/mcp/tools/spreadsheet-create.js.map +1 -1
- package/dist/esm/mcp/tools/spreadsheet-find.d.ts +1 -1
- package/dist/esm/mcp/tools/spreadsheet-find.js +2 -2
- package/dist/esm/mcp/tools/spreadsheet-find.js.map +1 -1
- package/dist/esm/mcp/tools/spreadsheet-rename.d.ts +1 -1
- package/dist/esm/mcp/tools/spreadsheet-rename.js +2 -2
- package/dist/esm/mcp/tools/spreadsheet-rename.js.map +1 -1
- package/dist/esm/mcp/tools/validation-set.d.ts +1 -1
- package/dist/esm/mcp/tools/validation-set.js +4 -4
- package/dist/esm/mcp/tools/validation-set.js.map +1 -1
- package/dist/esm/mcp/tools/values-batch-update.d.ts +1 -1
- package/dist/esm/mcp/tools/values-batch-update.js +5 -5
- package/dist/esm/mcp/tools/values-batch-update.js.map +1 -1
- package/dist/esm/mcp/tools/values-clear.d.ts +1 -1
- package/dist/esm/mcp/tools/values-clear.js +3 -3
- package/dist/esm/mcp/tools/values-clear.js.map +1 -1
- package/dist/esm/mcp/tools/values-csv-update.d.ts +1 -1
- package/dist/esm/mcp/tools/values-csv-update.js +4 -4
- package/dist/esm/mcp/tools/values-csv-update.js.map +1 -1
- package/dist/esm/mcp/tools/values-markdown-update.d.ts +1 -1
- package/dist/esm/mcp/tools/values-markdown-update.js +5 -5
- package/dist/esm/mcp/tools/values-markdown-update.js.map +1 -1
- package/dist/esm/mcp/tools/values-replace.d.ts +1 -1
- package/dist/esm/mcp/tools/values-replace.js +5 -5
- package/dist/esm/mcp/tools/values-replace.js.map +1 -1
- package/dist/esm/mcp/tools/values-search.d.ts +1 -1
- package/dist/esm/mcp/tools/values-search.js +3 -3
- package/dist/esm/mcp/tools/values-search.js.map +1 -1
- package/dist/esm/setup/http.d.ts +1 -1
- package/dist/esm/setup/http.js +21 -11
- package/dist/esm/setup/http.js.map +1 -1
- package/dist/esm/setup/stdio.d.ts +1 -1
- package/dist/esm/setup/stdio.js +1 -2
- package/dist/esm/setup/stdio.js.map +1 -1
- package/package.json +7 -13
|
@@ -9,7 +9,7 @@ Object.defineProperty(exports, "default", {
|
|
|
9
9
|
}
|
|
10
10
|
});
|
|
11
11
|
var _oauthgoogle = require("@mcp-z/oauth-google");
|
|
12
|
-
var
|
|
12
|
+
var _server = require("@mcp-z/server");
|
|
13
13
|
var _csvparse = require("csv-parse");
|
|
14
14
|
var _googleapis = require("googleapis");
|
|
15
15
|
var _zod = require("zod");
|
|
@@ -268,7 +268,7 @@ function handler(_0, _1) {
|
|
|
268
268
|
return String((_s_properties = s.properties) === null || _s_properties === void 0 ? void 0 : _s_properties.sheetId) === gid;
|
|
269
269
|
});
|
|
270
270
|
if (!(sheet === null || sheet === void 0 ? void 0 : sheet.properties)) {
|
|
271
|
-
throw new
|
|
271
|
+
throw new _server.ProtocolError(_server.ProtocolErrorCode.InvalidParams, "Sheet not found: ".concat(gid));
|
|
272
272
|
}
|
|
273
273
|
sheetTitle = (_sheet_properties_title = sheet.properties.title) !== null && _sheet_properties_title !== void 0 ? _sheet_properties_title : '';
|
|
274
274
|
// Streaming CSV processing state
|
|
@@ -396,7 +396,7 @@ function handler(_0, _1) {
|
|
|
396
396
|
];
|
|
397
397
|
case 15:
|
|
398
398
|
if (allRows.length === 0) {
|
|
399
|
-
throw new
|
|
399
|
+
throw new _server.ProtocolError(_server.ProtocolErrorCode.InvalidParams, 'CSV file is empty');
|
|
400
400
|
}
|
|
401
401
|
// Prepare data for update (all rows)
|
|
402
402
|
dataToWrite = allRows;
|
|
@@ -475,7 +475,7 @@ function handler(_0, _1) {
|
|
|
475
475
|
logger.error('sheets.values.csv-update error', {
|
|
476
476
|
error: message
|
|
477
477
|
});
|
|
478
|
-
throw new
|
|
478
|
+
throw new _server.ProtocolError(_server.ProtocolErrorCode.InternalError, "Error updating values from CSV: ".concat(message), {
|
|
479
479
|
stack: _instanceof(error, Error) ? error.stack : undefined
|
|
480
480
|
});
|
|
481
481
|
case 18:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-sheets/src/mcp/tools/values-csv-update.ts"],"sourcesContent":["/** Import CSV data to Google Sheets with range-based update (no deduplication) */\n\nimport type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { ToolModule } from '@mcp-z/server';\nimport type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';\nimport { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';\nimport { parse } from 'csv-parse';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\nimport { A1NotationSchema, SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\nimport { getCsvReadStream } from '../../spreadsheet/csv-streaming.ts';\n\n/** Batch size for Sheets API calls (1000 rows × avg 10 cols = 10K cells, well under 40K limit) */\nconst BATCH_SIZE = 1000;\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n sourceUri: z.string().trim().min(1).describe('CSV file URI (file://, http://, https://)'),\n startRange: A1NotationSchema.default('A1').describe('Top-left cell where CSV data starts (default: A1)'),\n valueInputOption: z.enum(['RAW', 'USER_ENTERED']).default('USER_ENTERED').describe('How to interpret values (RAW = exact, USER_ENTERED = parse formulas/dates)'),\n sourceHasHeaders: z.boolean().default(true).describe('First row is headers (metadata) - exclude from data range. Set to false to include first row as data.'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n gid: SheetGidOutput,\n spreadsheetTitle: z.string().describe('Spreadsheet title'),\n spreadsheetUrl: z.string().describe('Spreadsheet URL'),\n sheetTitle: z.string().describe('Sheet title'),\n sheetUrl: z.string().describe('Sheet URL'),\n updatedRange: z.string().describe('A1 notation range that was updated'),\n updatedRows: z.number().describe('Number of rows updated'),\n updatedColumns: z.number().describe('Number of columns updated'),\n updatedCells: z.number().describe('Number of cells updated'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Import CSV to sheet range. Overwrites existing data at startRange. Use rows-csv-append for database-style appends with deduplication.',\n inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ id, gid, sourceUri, startRange, valueInputOption = 'USER_ENTERED', sourceHasHeaders }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values.csv-update called', { id, gid, sourceUri, startRange, valueInputOption, sourceHasHeaders });\n\n try {\n const sheets = google.sheets({ version: 'v4', auth: extra.authContext.auth });\n\n // Get spreadsheet and sheet info in single API call\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'properties.title,spreadsheetUrl,sheets.properties.sheetId,sheets.properties.title',\n });\n\n const spreadsheetData = spreadsheetResponse.data;\n\n // Find the sheet by gid\n const sheet = spreadsheetData.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n if (!sheet?.properties) {\n throw new McpError(ErrorCode.InvalidParams, `Sheet not found: ${gid}`);\n }\n\n const sheetTitle = sheet.properties.title ?? '';\n\n // Streaming CSV processing state\n let sourceHeaders: string[] = [];\n const allRows: (string | number | boolean | null)[][] = [];\n let totalCols = 0;\n\n // Get readable stream from CSV URI (no temp files!)\n const readStream = await getCsvReadStream(sourceUri);\n\n // Create CSV parser with native streaming\n const parser = readStream.pipe(\n parse({\n columns: !!sourceHasHeaders, // Parse first row as column names if source has headers\n skip_empty_lines: true,\n trim: true,\n cast: true, // Auto-convert numbers/booleans\n relax_column_count: true,\n })\n );\n\n // Stream and collect all rows (with batching for very large files)\n for await (const record of parser) {\n if (sourceHasHeaders) {\n // Extract source headers from first record\n if (sourceHeaders.length === 0) {\n sourceHeaders = Object.keys(record as Record<string, unknown>);\n totalCols = sourceHeaders.length;\n logger.info('sheets.values.csv-update source headers', { sourceHeaders, totalCols });\n }\n\n // Convert record to row array (exclude source headers from data range)\n // CSV values are strings/numbers/booleans/nulls from the parser\n const row = sourceHeaders.map((header) => (record as Record<string, string | number | boolean | null>)[header] ?? null);\n allRows.push(row);\n } else {\n // sourceHasHeaders=false: record is an array, include all rows (including first row)\n const row = record as (string | number | boolean | null)[];\n allRows.push(row);\n\n if (totalCols === 0) {\n totalCols = row.length;\n }\n }\n }\n\n if (allRows.length === 0) {\n throw new McpError(ErrorCode.InvalidParams, 'CSV file is empty');\n }\n\n // Prepare data for update (all rows)\n const dataToWrite: (string | number | boolean | null)[][] = allRows;\n\n // For large datasets, use batchUpdate to write in chunks\n // This respects the 40K cell limit per request\n const batchRequests = [];\n const currentRow = startRange.match(/[A-Z]+(\\d+)/)?.[1] || '1';\n let currentRowNum = Number.parseInt(currentRow, 10);\n\n for (let i = 0; i < dataToWrite.length; i += BATCH_SIZE) {\n const batchData = dataToWrite.slice(i, i + BATCH_SIZE);\n const batchRange = `${sheetTitle}!${startRange.match(/[A-Z]+/)?.[0]}${currentRowNum}`;\n\n batchRequests.push({\n range: batchRange,\n values: batchData,\n });\n\n currentRowNum += batchData.length;\n }\n\n logger.info('sheets.values.csv-update batching', { totalBatches: batchRequests.length, batchSize: BATCH_SIZE });\n\n // Execute batch update\n const batchUpdateResponse = await sheets.spreadsheets.values.batchUpdate({\n spreadsheetId: id,\n requestBody: {\n valueInputOption,\n data: batchRequests,\n },\n });\n\n const totalUpdatedCells = batchUpdateResponse.data.totalUpdatedCells || 0;\n const totalUpdatedRows = batchUpdateResponse.data.totalUpdatedRows || 0;\n const totalUpdatedColumns = batchUpdateResponse.data.totalUpdatedColumns || 0;\n const firstUpdatedRange = batchUpdateResponse.data.responses?.[0]?.updatedRange || `${sheetTitle}!${startRange}`;\n\n logger.info('sheets.values.csv-update completed', { id, gid: sheet.properties.sheetId, updatedRange: firstUpdatedRange, updatedRows: totalUpdatedRows, sourceUri });\n\n const result: Output = {\n type: 'success' as const,\n id,\n gid: String(sheet.properties.sheetId ?? ''),\n spreadsheetTitle: spreadsheetData.properties?.title ?? '',\n spreadsheetUrl: spreadsheetData.spreadsheetUrl ?? `https://docs.google.com/spreadsheets/d/${id}`,\n sheetTitle,\n sheetUrl: `https://docs.google.com/spreadsheets/d/${id}/edit#gid=${sheet.properties.sheetId}`,\n updatedRange: firstUpdatedRange,\n updatedRows: totalUpdatedRows,\n updatedColumns: totalUpdatedColumns,\n updatedCells: totalUpdatedCells,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('sheets.values.csv-update error', { error: message });\n\n throw new McpError(ErrorCode.InternalError, `Error updating values from CSV: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-csv-update',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","BATCH_SIZE","inputSchema","z","object","id","SpreadsheetIdSchema","gid","SheetGidSchema","sourceUri","string","trim","min","describe","startRange","A1NotationSchema","default","valueInputOption","enum","sourceHasHeaders","boolean","successBranchSchema","type","literal","SpreadsheetIdOutput","SheetGidOutput","spreadsheetTitle","spreadsheetUrl","sheetTitle","sheetUrl","updatedRange","updatedRows","number","updatedColumns","updatedCells","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","sheet","spreadsheetData","batchUpdateResponse","sheets","spreadsheetResponse","sourceHeaders","allRows","totalCols","readStream","parser","dataToWrite","batchRequests","currentRow","currentRowNum","i","batchData","batchRange","totalUpdatedCells","totalUpdatedRows","totalUpdatedColumns","firstUpdatedRange","error","message","info","google","version","auth","authContext","spreadsheets","get","spreadsheetId","fields","data","find","s","String","properties","sheetId","McpError","ErrorCode","InvalidParams","title","getCsvReadStream","pipe","parse","columns","skip_empty_lines","cast","relax_column_count","record","length","Object","keys","row","map","header","push","match","Number","parseInt","slice","range","values","totalBatches","batchSize","batchUpdate","requestBody","responses","content","text","JSON","stringify","structuredContent","Error","InternalError","stack","undefined","name"],"mappings":"AAAA,gFAAgF;;;;+BAiMhF;;;eAAwBA;;;2BA9LA;qBAMY;wBACd;0BACC;mBACL;uBACyF;8BAC1E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,SAAQpD,MAAMsD,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAASzH;IACtB,OAAO;QACL0H,MAAM;QACNnF,QAAAA;QACAG,SAAAA;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-sheets/src/mcp/tools/values-csv-update.ts"],"sourcesContent":["/** Import CSV data to Google Sheets with range-based update (no deduplication) */\n\nimport type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { CallToolResult, ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { parse } from 'csv-parse';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\nimport { A1NotationSchema, SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\nimport { getCsvReadStream } from '../../spreadsheet/csv-streaming.ts';\n\n/** Batch size for Sheets API calls (1000 rows × avg 10 cols = 10K cells, well under 40K limit) */\nconst BATCH_SIZE = 1000;\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n sourceUri: z.string().trim().min(1).describe('CSV file URI (file://, http://, https://)'),\n startRange: A1NotationSchema.default('A1').describe('Top-left cell where CSV data starts (default: A1)'),\n valueInputOption: z.enum(['RAW', 'USER_ENTERED']).default('USER_ENTERED').describe('How to interpret values (RAW = exact, USER_ENTERED = parse formulas/dates)'),\n sourceHasHeaders: z.boolean().default(true).describe('First row is headers (metadata) - exclude from data range. Set to false to include first row as data.'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n gid: SheetGidOutput,\n spreadsheetTitle: z.string().describe('Spreadsheet title'),\n spreadsheetUrl: z.string().describe('Spreadsheet URL'),\n sheetTitle: z.string().describe('Sheet title'),\n sheetUrl: z.string().describe('Sheet URL'),\n updatedRange: z.string().describe('A1 notation range that was updated'),\n updatedRows: z.number().describe('Number of rows updated'),\n updatedColumns: z.number().describe('Number of columns updated'),\n updatedCells: z.number().describe('Number of cells updated'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Import CSV to sheet range. Overwrites existing data at startRange. Use rows-csv-append for database-style appends with deduplication.',\n inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ id, gid, sourceUri, startRange, valueInputOption = 'USER_ENTERED', sourceHasHeaders }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values.csv-update called', { id, gid, sourceUri, startRange, valueInputOption, sourceHasHeaders });\n\n try {\n const sheets = google.sheets({ version: 'v4', auth: extra.authContext.auth });\n\n // Get spreadsheet and sheet info in single API call\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'properties.title,spreadsheetUrl,sheets.properties.sheetId,sheets.properties.title',\n });\n\n const spreadsheetData = spreadsheetResponse.data;\n\n // Find the sheet by gid\n const sheet = spreadsheetData.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n if (!sheet?.properties) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Sheet not found: ${gid}`);\n }\n\n const sheetTitle = sheet.properties.title ?? '';\n\n // Streaming CSV processing state\n let sourceHeaders: string[] = [];\n const allRows: (string | number | boolean | null)[][] = [];\n let totalCols = 0;\n\n // Get readable stream from CSV URI (no temp files!)\n const readStream = await getCsvReadStream(sourceUri);\n\n // Create CSV parser with native streaming\n const parser = readStream.pipe(\n parse({\n columns: !!sourceHasHeaders, // Parse first row as column names if source has headers\n skip_empty_lines: true,\n trim: true,\n cast: true, // Auto-convert numbers/booleans\n relax_column_count: true,\n })\n );\n\n // Stream and collect all rows (with batching for very large files)\n for await (const record of parser) {\n if (sourceHasHeaders) {\n // Extract source headers from first record\n if (sourceHeaders.length === 0) {\n sourceHeaders = Object.keys(record as Record<string, unknown>);\n totalCols = sourceHeaders.length;\n logger.info('sheets.values.csv-update source headers', { sourceHeaders, totalCols });\n }\n\n // Convert record to row array (exclude source headers from data range)\n // CSV values are strings/numbers/booleans/nulls from the parser\n const row = sourceHeaders.map((header) => (record as Record<string, string | number | boolean | null>)[header] ?? null);\n allRows.push(row);\n } else {\n // sourceHasHeaders=false: record is an array, include all rows (including first row)\n const row = record as (string | number | boolean | null)[];\n allRows.push(row);\n\n if (totalCols === 0) {\n totalCols = row.length;\n }\n }\n }\n\n if (allRows.length === 0) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'CSV file is empty');\n }\n\n // Prepare data for update (all rows)\n const dataToWrite: (string | number | boolean | null)[][] = allRows;\n\n // For large datasets, use batchUpdate to write in chunks\n // This respects the 40K cell limit per request\n const batchRequests = [];\n const currentRow = startRange.match(/[A-Z]+(\\d+)/)?.[1] || '1';\n let currentRowNum = Number.parseInt(currentRow, 10);\n\n for (let i = 0; i < dataToWrite.length; i += BATCH_SIZE) {\n const batchData = dataToWrite.slice(i, i + BATCH_SIZE);\n const batchRange = `${sheetTitle}!${startRange.match(/[A-Z]+/)?.[0]}${currentRowNum}`;\n\n batchRequests.push({\n range: batchRange,\n values: batchData,\n });\n\n currentRowNum += batchData.length;\n }\n\n logger.info('sheets.values.csv-update batching', { totalBatches: batchRequests.length, batchSize: BATCH_SIZE });\n\n // Execute batch update\n const batchUpdateResponse = await sheets.spreadsheets.values.batchUpdate({\n spreadsheetId: id,\n requestBody: {\n valueInputOption,\n data: batchRequests,\n },\n });\n\n const totalUpdatedCells = batchUpdateResponse.data.totalUpdatedCells || 0;\n const totalUpdatedRows = batchUpdateResponse.data.totalUpdatedRows || 0;\n const totalUpdatedColumns = batchUpdateResponse.data.totalUpdatedColumns || 0;\n const firstUpdatedRange = batchUpdateResponse.data.responses?.[0]?.updatedRange || `${sheetTitle}!${startRange}`;\n\n logger.info('sheets.values.csv-update completed', { id, gid: sheet.properties.sheetId, updatedRange: firstUpdatedRange, updatedRows: totalUpdatedRows, sourceUri });\n\n const result: Output = {\n type: 'success' as const,\n id,\n gid: String(sheet.properties.sheetId ?? ''),\n spreadsheetTitle: spreadsheetData.properties?.title ?? '',\n spreadsheetUrl: spreadsheetData.spreadsheetUrl ?? `https://docs.google.com/spreadsheets/d/${id}`,\n sheetTitle,\n sheetUrl: `https://docs.google.com/spreadsheets/d/${id}/edit#gid=${sheet.properties.sheetId}`,\n updatedRange: firstUpdatedRange,\n updatedRows: totalUpdatedRows,\n updatedColumns: totalUpdatedColumns,\n updatedCells: totalUpdatedCells,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('sheets.values.csv-update error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error updating values from CSV: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-csv-update',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","BATCH_SIZE","inputSchema","z","object","id","SpreadsheetIdSchema","gid","SheetGidSchema","sourceUri","string","trim","min","describe","startRange","A1NotationSchema","default","valueInputOption","enum","sourceHasHeaders","boolean","successBranchSchema","type","literal","SpreadsheetIdOutput","SheetGidOutput","spreadsheetTitle","spreadsheetUrl","sheetTitle","sheetUrl","updatedRange","updatedRows","number","updatedColumns","updatedCells","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","sheet","spreadsheetData","batchUpdateResponse","sheets","spreadsheetResponse","sourceHeaders","allRows","totalCols","readStream","parser","dataToWrite","batchRequests","currentRow","currentRowNum","i","batchData","batchRange","totalUpdatedCells","totalUpdatedRows","totalUpdatedColumns","firstUpdatedRange","error","message","info","google","version","auth","authContext","spreadsheets","get","spreadsheetId","fields","data","find","s","String","properties","sheetId","ProtocolError","ProtocolErrorCode","InvalidParams","title","getCsvReadStream","pipe","parse","columns","skip_empty_lines","cast","relax_column_count","record","length","Object","keys","row","map","header","push","match","Number","parseInt","slice","range","values","totalBatches","batchSize","batchUpdate","requestBody","responses","content","text","JSON","stringify","structuredContent","Error","InternalError","stack","undefined","name"],"mappings":"AAAA,gFAAgF;;;;+BAgMhF;;;eAAwBA;;;2BA7LA;sBAKyB;wBAC3B;0BACC;mBACL;uBACyF;8BAC1E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AARjC,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAUR,gGAAgG,GAChG,IAAME,aAAa;AAEnB,IAAMC,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,IAAIC,4BAAmB;IACvBC,KAAKC,uBAAc;IACnBC,WAAWN,MAAC,CAACO,MAAM,GAAGC,IAAI,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;IAC7CC,YAAYC,yBAAgB,CAACC,OAAO,CAAC,MAAMH,QAAQ,CAAC;IACpDI,kBAAkBd,MAAC,CAACe,IAAI,CAAC;QAAC;QAAO;KAAe,EAAEF,OAAO,CAAC,gBAAgBH,QAAQ,CAAC;IACnFM,kBAAkBhB,MAAC,CAACiB,OAAO,GAAGJ,OAAO,CAAC,MAAMH,QAAQ,CAAC;AACvD;AAEA,IAAMQ,sBAAsBlB,MAAC,CAACC,MAAM,CAAC;IACnCkB,MAAMnB,MAAC,CAACoB,OAAO,CAAC;IAChBlB,IAAImB,4BAAmB;IACvBjB,KAAKkB,uBAAc;IACnBC,kBAAkBvB,MAAC,CAACO,MAAM,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dhC,aAAa8B;wBACb5B,gBAAgB6B;wBAChB5B,cAAc0B;oBAChB;oBAEA;;wBAAO;4BACLmD,OAAO;gCAAG;oCAAEzF,MAAM;oCAAiB0F,MAAMC,KAAKC,SAAS,CAAC3E;gCAAQ;;4BAChE4E,mBAAmB;gCAAE5E,QAAAA;4BAAO;wBAC9B;;;oBACOyB;oBACDC,UAAUD,AAAK,YAALA,OAAiBoD,SAAQpD,MAAMC,OAAO,GAAGa,OAAOd;oBAChEtB,OAAOsB,KAAK,CAAC,kCAAkC;wBAAEA,OAAOC;oBAAQ;oBAEhE,MAAM,IAAIgB,qBAAa,CAACC,yBAAiB,CAACmC,aAAa,EAAE,AAAC,mCAA0C,OAARpD,UAAW;wBACrGqD,OAAOtD,AAAK,YAALA,OAAiBoD,SAAQpD,MAAMsD,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAASzH;IACtB,OAAO;QACL0H,MAAM;QACNnF,QAAAA;QACAG,SAAAA;IACF;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { EnrichedExtra } from '@mcp-z/oauth-google';
|
|
2
|
-
import type { CallToolResult } from '@
|
|
2
|
+
import type { CallToolResult } from '@mcp-z/server';
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
declare const inputSchema: z.ZodObject<{
|
|
5
5
|
id: z.ZodString;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { EnrichedExtra } from '@mcp-z/oauth-google';
|
|
2
|
-
import type { CallToolResult } from '@
|
|
2
|
+
import type { CallToolResult } from '@mcp-z/server';
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
declare const inputSchema: z.ZodObject<{
|
|
5
5
|
id: z.ZodString;
|
|
@@ -9,7 +9,7 @@ Object.defineProperty(exports, "default", {
|
|
|
9
9
|
}
|
|
10
10
|
});
|
|
11
11
|
var _oauthgoogle = require("@mcp-z/oauth-google");
|
|
12
|
-
var
|
|
12
|
+
var _server = require("@mcp-z/server");
|
|
13
13
|
var _googleapis = require("googleapis");
|
|
14
14
|
var _zod = require("zod");
|
|
15
15
|
var _indexts = require("../../schemas/index.js");
|
|
@@ -230,7 +230,7 @@ function handler(_0, _1) {
|
|
|
230
230
|
gid: gid,
|
|
231
231
|
requestCount: requests.length
|
|
232
232
|
});
|
|
233
|
-
throw new
|
|
233
|
+
throw new _server.ProtocolError(_server.ProtocolErrorCode.InvalidParams, "Sheet not found: ".concat(gid));
|
|
234
234
|
}
|
|
235
235
|
sheetTitle = (_sheet_properties_title = sheet.properties.title) !== null && _sheet_properties_title !== void 0 ? _sheet_properties_title : gid;
|
|
236
236
|
// googleapis types sheetId as `number | null | undefined`; coerce for rangeReferenceToGridRange below (same pattern as values-batch-update.ts's sheetGid).
|
|
@@ -376,8 +376,8 @@ function handler(_0, _1) {
|
|
|
376
376
|
];
|
|
377
377
|
case 4:
|
|
378
378
|
error = _state.sent();
|
|
379
|
-
// Re-throw
|
|
380
|
-
if (_instanceof(error,
|
|
379
|
+
// Re-throw ProtocolError as-is
|
|
380
|
+
if (_instanceof(error, _server.ProtocolError)) {
|
|
381
381
|
throw error;
|
|
382
382
|
}
|
|
383
383
|
message1 = _instanceof(error, Error) ? error.message : String(error);
|
|
@@ -387,7 +387,7 @@ function handler(_0, _1) {
|
|
|
387
387
|
requestCount: requests.length,
|
|
388
388
|
error: message1
|
|
389
389
|
});
|
|
390
|
-
throw new
|
|
390
|
+
throw new _server.ProtocolError(_server.ProtocolErrorCode.InternalError, "Error writing markdown to cells: ".concat(message1), {
|
|
391
391
|
stack: _instanceof(error, Error) ? error.stack : undefined
|
|
392
392
|
});
|
|
393
393
|
case 5:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-sheets/src/mcp/tools/values-markdown-update.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { ToolModule } from '@mcp-z/server';\nimport type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';\nimport { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';\nimport { google, type sheets_v4 } from 'googleapis';\nimport { z } from 'zod';\nimport { SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\nimport { buildTextFormatRuns, parseInlineMarkdown } from '../../spreadsheet/markdown-runs.ts';\nimport { parseA1Notation, rangeReferenceToGridRange } from '../../spreadsheet/range-operations.ts';\n\n// Input schema for a single markdown-cell request\nconst MarkdownCellRequestSchema = z.object({\n cell: z.string().min(1).describe('Single-cell A1 reference (e.g., \"I2\"). Multi-cell ranges (e.g., \"A1:B2\") are rejected as a per-request failure.'),\n text: z.string().describe('Cell content as inline markdown: [label](url) links, bare URLs, **bold**, *italic*, ~~strikethrough~~. Block syntax and other unsupported markdown is written as literal text.'),\n});\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n requests: z.array(MarkdownCellRequestSchema).min(1).max(50).describe('Array of cell markdown requests. Batch multiple cells for efficiency.'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n gid: SheetGidOutput,\n sheetTitle: z.string().describe('Title of the updated sheet'),\n sheetUrl: z.string().describe('URL of the updated sheet'),\n successCount: z.number().int().nonnegative().describe('Number of cells successfully written'),\n cells: z\n .array(\n z.object({\n cell: z.string().describe('A1 reference of the cell that was written'),\n text: z.string().describe('Resolved plain text written to the cell (markdown syntax stripped/literalized)'),\n linkCount: z.number().int().nonnegative().describe('Number of clickable links written into the cell'),\n })\n )\n .describe('Cells successfully written'),\n failedCells: z\n .array(\n z.object({\n cell: z.string().describe('A1 reference that failed'),\n error: z.string().describe('Why the cell failed (e.g., not a single-cell reference)'),\n })\n )\n .optional()\n .describe('Only populated if some cells failed'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description:\n 'Replace cell content with text parsed from inline markdown. Supports [label](url) links, bare URLs, **bold**, *italic*, ~~strikethrough~~ — the only way to put MULTIPLE clickable links in one cell. Block syntax (headers, lists, tables) and other unsupported markdown is written as literal text. Writes text cells only — no formula or number coercion. For whole-cell formatting (colors, borders, number formats) use cells-format.',\n inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ id, gid, requests }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values.markdownUpdate called', {\n id,\n gid,\n requestCount: requests.length,\n });\n\n try {\n const sheets = google.sheets({ version: 'v4', auth: extra.authContext.auth });\n\n // Get spreadsheet and sheet info in single API call\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'sheets.properties.sheetId,sheets.properties.title',\n });\n\n // Find sheet by gid\n const sheet = spreadsheetResponse.data.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n if (!sheet?.properties) {\n logger.info('Sheet not found for markdown update', { id, gid, requestCount: requests.length });\n throw new McpError(ErrorCode.InvalidParams, `Sheet not found: ${gid}`);\n }\n\n const sheetTitle = sheet.properties.title ?? gid;\n // googleapis types sheetId as `number | null | undefined`; coerce for rangeReferenceToGridRange below (same pattern as values-batch-update.ts's sheetGid).\n const sheetId = sheet.properties.sheetId ?? 0;\n const sheetUrl = `https://docs.google.com/spreadsheets/d/${id}/edit#gid=${sheetId}`;\n\n // Build one updateCells request per cell\n const batchRequests: sheets_v4.Schema$Request[] = [];\n const cells: Array<{ cell: string; text: string; linkCount: number }> = [];\n const failedCells: Array<{ cell: string; error: string }> = [];\n\n for (const request of requests) {\n try {\n // Parse A1 notation and reject anything that isn't a single cell\n const rangeRef = parseA1Notation(request.cell);\n if (rangeRef.type !== 'cell') {\n throw new Error(`Not a single-cell reference: \"${request.cell}\"`);\n }\n\n const gridRange = rangeReferenceToGridRange(rangeRef, sheetId);\n const parsed = parseInlineMarkdown(request.text);\n const runs = buildTextFormatRuns(parsed);\n\n batchRequests.push({\n updateCells: {\n range: gridRange,\n rows: [\n {\n values: [\n {\n userEnteredValue: { stringValue: parsed.text },\n textFormatRuns: runs,\n },\n ],\n },\n ],\n fields: 'userEnteredValue,textFormatRuns',\n },\n });\n cells.push({ cell: request.cell, text: parsed.text, linkCount: parsed.linkCount });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.info('Failed to parse cell for markdown update', {\n cell: request.cell,\n error: message,\n });\n failedCells.push({\n cell: request.cell,\n error: `Failed to parse cell: ${message}`,\n });\n }\n }\n\n // Early return if all cells failed\n if (batchRequests.length === 0) {\n const result: Output = {\n type: 'success' as const,\n id,\n gid: String(sheetId),\n sheetTitle,\n sheetUrl,\n successCount: 0,\n cells: [],\n failedCells: failedCells.length > 0 ? failedCells : undefined,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n }\n\n logger.info('sheets.values.markdownUpdate executing batch request', {\n spreadsheetId: id,\n sheetTitle,\n batchRequestsCount: batchRequests.length,\n });\n\n // Execute the batch update\n await sheets.spreadsheets.batchUpdate({\n spreadsheetId: id,\n requestBody: {\n requests: batchRequests,\n },\n });\n\n logger.info('sheets.values.markdownUpdate completed successfully', {\n successCount: cells.length,\n failedCount: failedCells.length,\n });\n\n const result: Output = {\n type: 'success' as const,\n id,\n gid: String(sheetId),\n sheetTitle,\n sheetUrl,\n successCount: cells.length,\n cells,\n failedCells: failedCells.length > 0 ? failedCells : undefined,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n // Re-throw McpError as-is\n if (error instanceof McpError) {\n throw error;\n }\n\n const message = error instanceof Error ? error.message : String(error);\n logger.error('Markdown update operation failed', {\n id,\n gid,\n requestCount: requests.length,\n error: message,\n });\n\n throw new McpError(ErrorCode.InternalError, `Error writing markdown to cells: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-markdown-update',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","MarkdownCellRequestSchema","z","object","cell","string","min","describe","text","inputSchema","id","SpreadsheetIdSchema","gid","SheetGidSchema","requests","array","max","successBranchSchema","type","literal","SpreadsheetIdOutput","SheetGidOutput","sheetTitle","sheetUrl","successCount","number","int","nonnegative","cells","linkCount","failedCells","error","optional","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","sheet","spreadsheetResponse","sheets","sheetId","batchRequests","request","rangeRef","gridRange","parsed","runs","message","info","requestCount","length","google","version","auth","authContext","spreadsheets","get","spreadsheetId","fields","data","find","s","String","properties","McpError","ErrorCode","InvalidParams","title","parseA1Notation","Error","rangeReferenceToGridRange","parseInlineMarkdown","buildTextFormatRuns","push","updateCells","range","rows","values","userEnteredValue","stringValue","textFormatRuns","undefined","content","JSON","stringify","structuredContent","batchRequestsCount","batchUpdate","requestBody","failedCount","InternalError","stack","name"],"mappings":";;;;+BAwNA;;;eAAwBA;;;2BAvNA;qBAMY;0BACG;mBACrB;uBACuE;8BAChC;iCACE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAT3D,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAWR,kDAAkD;AAClD,IAAME,4BAA4BC,MAAC,CAACC,MAAM,CAAC;IACzCC,MAAMF,MAAC,CAACG,MAAM,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;IACjCC,MAAMN,MAAC,CAACG,MAAM,GAAGE,QAAQ,CAAC;AAC5B;AAEA,IAAME,cAAcP,MAA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;;oBACON;oBACP,0BAA0B;oBAC1B,IAAIA,AAAK,YAALA,OAAiBqC,eAAQ,GAAE;wBAC7B,MAAMrC;oBACR;oBAEMoB,WAAUpB,AAAK,YAALA,OAAiB0C,SAAQ1C,MAAMoB,OAAO,GAAGe,OAAOnC;oBAChES,OAAOT,KAAK,CAAC,oCAAoC;wBAC/CrB,IAAAA;wBACAE,KAAAA;wBACAyC,cAAcvC,SAASwC,MAAM;wBAC7BvB,OAAOoB;oBACT;oBAEA,MAAM,IAAIiB,eAAQ,CAACC,gBAAS,CAACyB,aAAa,EAAE,AAAC,oCAA2C,OAAR3C,WAAW;wBACzF4C,OAAOhE,AAAK,YAALA,OAAiB0C,SAAQ1C,MAAMgE,KAAK,GAAGV;oBAChD;;;;;;;IAEJ;;AAEe,SAASvF;IACtB,OAAO;QACLkG,MAAM;QACN7D,QAAAA;QACAG,SAAAA;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-sheets/src/mcp/tools/values-markdown-update.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { CallToolResult, ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { google, type sheets_v4 } from 'googleapis';\nimport { z } from 'zod';\nimport { SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\nimport { buildTextFormatRuns, parseInlineMarkdown } from '../../spreadsheet/markdown-runs.ts';\nimport { parseA1Notation, rangeReferenceToGridRange } from '../../spreadsheet/range-operations.ts';\n\n// Input schema for a single markdown-cell request\nconst MarkdownCellRequestSchema = z.object({\n cell: z.string().min(1).describe('Single-cell A1 reference (e.g., \"I2\"). Multi-cell ranges (e.g., \"A1:B2\") are rejected as a per-request failure.'),\n text: z.string().describe('Cell content as inline markdown: [label](url) links, bare URLs, **bold**, *italic*, ~~strikethrough~~. Block syntax and other unsupported markdown is written as literal text.'),\n});\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n requests: z.array(MarkdownCellRequestSchema).min(1).max(50).describe('Array of cell markdown requests. Batch multiple cells for efficiency.'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n gid: SheetGidOutput,\n sheetTitle: z.string().describe('Title of the updated sheet'),\n sheetUrl: z.string().describe('URL of the updated sheet'),\n successCount: z.number().int().nonnegative().describe('Number of cells successfully written'),\n cells: z\n .array(\n z.object({\n cell: z.string().describe('A1 reference of the cell that was written'),\n text: z.string().describe('Resolved plain text written to the cell (markdown syntax stripped/literalized)'),\n linkCount: z.number().int().nonnegative().describe('Number of clickable links written into the cell'),\n })\n )\n .describe('Cells successfully written'),\n failedCells: z\n .array(\n z.object({\n cell: z.string().describe('A1 reference that failed'),\n error: z.string().describe('Why the cell failed (e.g., not a single-cell reference)'),\n })\n )\n .optional()\n .describe('Only populated if some cells failed'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description:\n 'Replace cell content with text parsed from inline markdown. Supports [label](url) links, bare URLs, **bold**, *italic*, ~~strikethrough~~ — the only way to put MULTIPLE clickable links in one cell. Block syntax (headers, lists, tables) and other unsupported markdown is written as literal text. Writes text cells only — no formula or number coercion. For whole-cell formatting (colors, borders, number formats) use cells-format.',\n inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ id, gid, requests }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values.markdownUpdate called', {\n id,\n gid,\n requestCount: requests.length,\n });\n\n try {\n const sheets = google.sheets({ version: 'v4', auth: extra.authContext.auth });\n\n // Get spreadsheet and sheet info in single API call\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'sheets.properties.sheetId,sheets.properties.title',\n });\n\n // Find sheet by gid\n const sheet = spreadsheetResponse.data.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n if (!sheet?.properties) {\n logger.info('Sheet not found for markdown update', { id, gid, requestCount: requests.length });\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Sheet not found: ${gid}`);\n }\n\n const sheetTitle = sheet.properties.title ?? gid;\n // googleapis types sheetId as `number | null | undefined`; coerce for rangeReferenceToGridRange below (same pattern as values-batch-update.ts's sheetGid).\n const sheetId = sheet.properties.sheetId ?? 0;\n const sheetUrl = `https://docs.google.com/spreadsheets/d/${id}/edit#gid=${sheetId}`;\n\n // Build one updateCells request per cell\n const batchRequests: sheets_v4.Schema$Request[] = [];\n const cells: Array<{ cell: string; text: string; linkCount: number }> = [];\n const failedCells: Array<{ cell: string; error: string }> = [];\n\n for (const request of requests) {\n try {\n // Parse A1 notation and reject anything that isn't a single cell\n const rangeRef = parseA1Notation(request.cell);\n if (rangeRef.type !== 'cell') {\n throw new Error(`Not a single-cell reference: \"${request.cell}\"`);\n }\n\n const gridRange = rangeReferenceToGridRange(rangeRef, sheetId);\n const parsed = parseInlineMarkdown(request.text);\n const runs = buildTextFormatRuns(parsed);\n\n batchRequests.push({\n updateCells: {\n range: gridRange,\n rows: [\n {\n values: [\n {\n userEnteredValue: { stringValue: parsed.text },\n textFormatRuns: runs,\n },\n ],\n },\n ],\n fields: 'userEnteredValue,textFormatRuns',\n },\n });\n cells.push({ cell: request.cell, text: parsed.text, linkCount: parsed.linkCount });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.info('Failed to parse cell for markdown update', {\n cell: request.cell,\n error: message,\n });\n failedCells.push({\n cell: request.cell,\n error: `Failed to parse cell: ${message}`,\n });\n }\n }\n\n // Early return if all cells failed\n if (batchRequests.length === 0) {\n const result: Output = {\n type: 'success' as const,\n id,\n gid: String(sheetId),\n sheetTitle,\n sheetUrl,\n successCount: 0,\n cells: [],\n failedCells: failedCells.length > 0 ? failedCells : undefined,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n }\n\n logger.info('sheets.values.markdownUpdate executing batch request', {\n spreadsheetId: id,\n sheetTitle,\n batchRequestsCount: batchRequests.length,\n });\n\n // Execute the batch update\n await sheets.spreadsheets.batchUpdate({\n spreadsheetId: id,\n requestBody: {\n requests: batchRequests,\n },\n });\n\n logger.info('sheets.values.markdownUpdate completed successfully', {\n successCount: cells.length,\n failedCount: failedCells.length,\n });\n\n const result: Output = {\n type: 'success' as const,\n id,\n gid: String(sheetId),\n sheetTitle,\n sheetUrl,\n successCount: cells.length,\n cells,\n failedCells: failedCells.length > 0 ? failedCells : undefined,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n // Re-throw ProtocolError as-is\n if (error instanceof ProtocolError) {\n throw error;\n }\n\n const message = error instanceof Error ? error.message : String(error);\n logger.error('Markdown update operation failed', {\n id,\n gid,\n requestCount: requests.length,\n error: message,\n });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error writing markdown to cells: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-markdown-update',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","MarkdownCellRequestSchema","z","object","cell","string","min","describe","text","inputSchema","id","SpreadsheetIdSchema","gid","SheetGidSchema","requests","array","max","successBranchSchema","type","literal","SpreadsheetIdOutput","SheetGidOutput","sheetTitle","sheetUrl","successCount","number","int","nonnegative","cells","linkCount","failedCells","error","optional","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","sheet","spreadsheetResponse","sheets","sheetId","batchRequests","request","rangeRef","gridRange","parsed","runs","message","info","requestCount","length","google","version","auth","authContext","spreadsheets","get","spreadsheetId","fields","data","find","s","String","properties","ProtocolError","ProtocolErrorCode","InvalidParams","title","parseA1Notation","Error","rangeReferenceToGridRange","parseInlineMarkdown","buildTextFormatRuns","push","updateCells","range","rows","values","userEnteredValue","stringValue","textFormatRuns","undefined","content","JSON","stringify","structuredContent","batchRequestsCount","batchUpdate","requestBody","failedCount","InternalError","stack","name"],"mappings":";;;;+BAuNA;;;eAAwBA;;;2BAtNA;sBAKyB;0BACV;mBACrB;uBACuE;8BAChC;iCACE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAR3D,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAUR,kDAAkD;AAClD,IAAME,4BAA4BC,MAAC,CAACC,MAAM,CAAC;IACzCC,MAAMF,MAAC,CAACG,MAAM,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;IACjCC,MAAMN,MAAC,CAACG,MAAM,GAAGE,QAAQ,CAAC;AAC5B;AAEA,IAAME,cAAcP,MAAC,CAACC,MAAM,CAAC;IAC3BO,IAAIC,4BAAmB;IACvBC,KAAKC,uBAAc;IACnBC,UAAUZ,MAAC,CAACa,KAAK,CAACd,2BAA2BK,GAAG,CAAC,GAAGU,GAAG,CAAC,IAAIT,QAAQ,CAAC;AACvE;AAEA,IAAMU,sBAAsBf,MAAC,CAACC,MAAM,CAAC;IACnCe,MAAMhB,MAAC,CAACiB,OAAO,CAAC;IAChBT,IAAIU,4BAAmB;IACvBR,KAAKS,uBAAc;IACnBC,YAAYpB,MAAC,CAACG,MAAM,GAAGE,QAAQ,CAAC;IAChCgB,UAAUrB,MAAC,CAACG,MAAM,GAAGE,QAAQ,CAAC;IAC9BiB,cAActB,MAAC,CAACuB,MAAM,GAAGC,GAAG,GAAGC,WAAW,GAAGpB,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AAEe,SAASvF;IACtB,OAAO;QACLkG,MAAM;QACN7D,QAAAA;QACAG,SAAAA;IACF;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { EnrichedExtra } from '@mcp-z/oauth-google';
|
|
2
|
-
import type { CallToolResult } from '@
|
|
2
|
+
import type { CallToolResult } from '@mcp-z/server';
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
declare const inputSchema: z.ZodObject<{
|
|
5
5
|
id: z.ZodString;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { EnrichedExtra } from '@mcp-z/oauth-google';
|
|
2
|
-
import type { CallToolResult } from '@
|
|
2
|
+
import type { CallToolResult } from '@mcp-z/server';
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
declare const inputSchema: z.ZodObject<{
|
|
5
5
|
id: z.ZodString;
|
|
@@ -9,7 +9,7 @@ Object.defineProperty(exports, "default", {
|
|
|
9
9
|
}
|
|
10
10
|
});
|
|
11
11
|
var _oauthgoogle = require("@mcp-z/oauth-google");
|
|
12
|
-
var
|
|
12
|
+
var _server = require("@mcp-z/server");
|
|
13
13
|
var _googleapis = require("googleapis");
|
|
14
14
|
var _zod = require("zod");
|
|
15
15
|
var _indexts = require("../../schemas/index.js");
|
|
@@ -275,12 +275,12 @@ function handler(_0, _1) {
|
|
|
275
275
|
return String((_s_properties = s.properties) === null || _s_properties === void 0 ? void 0 : _s_properties.sheetId) === gid;
|
|
276
276
|
});
|
|
277
277
|
if (!sheet) {
|
|
278
|
-
throw new
|
|
278
|
+
throw new _server.ProtocolError(_server.ProtocolErrorCode.InvalidParams, "Sheet not found: ".concat(gid));
|
|
279
279
|
}
|
|
280
280
|
// Note: sheetId can be 0 which is falsy, so check explicitly for undefined/null
|
|
281
281
|
sheetId = (_sheet_properties = sheet.properties) === null || _sheet_properties === void 0 ? void 0 : _sheet_properties.sheetId;
|
|
282
282
|
if (sheetId === undefined || sheetId === null) {
|
|
283
|
-
throw new
|
|
283
|
+
throw new _server.ProtocolError(_server.ProtocolErrorCode.InternalError, 'Sheet properties not available');
|
|
284
284
|
}
|
|
285
285
|
if (!range) {
|
|
286
286
|
// gid but no range = search specific sheet
|
|
@@ -339,7 +339,7 @@ function handler(_0, _1) {
|
|
|
339
339
|
];
|
|
340
340
|
case 6:
|
|
341
341
|
error = _state.sent();
|
|
342
|
-
if (_instanceof(error,
|
|
342
|
+
if (_instanceof(error, _server.ProtocolError)) {
|
|
343
343
|
throw error;
|
|
344
344
|
}
|
|
345
345
|
message = _instanceof(error, Error) ? error.message : String(error);
|
|
@@ -351,7 +351,7 @@ function handler(_0, _1) {
|
|
|
351
351
|
range: range,
|
|
352
352
|
error: message
|
|
353
353
|
});
|
|
354
|
-
throw new
|
|
354
|
+
throw new _server.ProtocolError(_server.ProtocolErrorCode.InternalError, "Error replacing values: ".concat(message), {
|
|
355
355
|
stack: _instanceof(error, Error) ? error.stack : undefined
|
|
356
356
|
});
|
|
357
357
|
case 7:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-sheets/src/mcp/tools/values-replace.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { ToolModule } from '@mcp-z/server';\nimport type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';\nimport { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';\nimport { google, type sheets_v4 } from 'googleapis';\nimport { z } from 'zod';\nimport { A1NotationSchema, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\nimport { parseA1Notation, rangeReferenceToGridRange } from '../../spreadsheet/range-operations.ts';\n\nconst inputSchema = z\n .object({\n id: SpreadsheetIdSchema,\n find: z.string().min(1).describe('Text or regex pattern to find'),\n replacement: z.string().describe('Replacement text. Use $1, $2 for regex capture groups. Empty string deletes matches.'),\n\n // Scope - defaults to all sheets if neither specified\n gid: SheetGidSchema.optional().describe('Limit to specific sheet. If omitted, searches all sheets.'),\n range: A1NotationSchema.optional().describe('Limit to specific A1 range within the sheet (requires gid)'),\n\n // Match options\n matchCase: z.boolean().optional().describe('Case-sensitive matching'),\n matchEntireCell: z.boolean().optional().describe('Only match entire cell content'),\n searchByRegex: z.boolean().optional().describe('Treat find as RE2 regex'),\n includeFormulas: z.boolean().optional().describe('Search within formula text'),\n })\n .refine((data) => !(data.range && !data.gid), { message: 'range requires gid' });\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n spreadsheetUrl: z.string().describe('URL of the spreadsheet'),\n occurrencesChanged: z.number().int().nonnegative().describe('Total replacements made'),\n valuesChanged: z.number().int().nonnegative().describe('Number of non-formula cells changed'),\n formulasChanged: z.number().int().nonnegative().describe('Number of formula cells changed'),\n rowsChanged: z.number().int().nonnegative().describe('Number of rows with replacements'),\n sheetsChanged: z.number().int().nonnegative().describe('Number of sheets with replacements'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Find and replace text across a spreadsheet. Searches all sheets by default, or limit with gid/range. Supports regex with capture groups ($1, $2).',\n inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ id, find, replacement, gid, range, matchCase, matchEntireCell, searchByRegex, includeFormulas }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values-replace called', { id, find, replacement, gid, range });\n\n try {\n const sheets = google.sheets({ version: 'v4', auth: extra.authContext.auth });\n\n // Build FindReplaceRequest - only include defined options\n const findReplaceRequest: sheets_v4.Schema$FindReplaceRequest = {\n find,\n replacement,\n ...(matchCase !== undefined && { matchCase }),\n ...(matchEntireCell !== undefined && { matchEntireCell }),\n ...(searchByRegex !== undefined && { searchByRegex }),\n ...(includeFormulas !== undefined && { includeFormulas }),\n };\n\n // Set scope based on gid/range\n if (!gid) {\n // No gid = search all sheets\n findReplaceRequest.allSheets = true;\n } else {\n // Need to resolve sheet to get numeric sheetId\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'sheets.properties.sheetId,sheets.properties.title',\n });\n\n const sheet = spreadsheetResponse.data.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n if (!sheet) {\n throw new McpError(ErrorCode.InvalidParams, `Sheet not found: ${gid}`);\n }\n\n // Note: sheetId can be 0 which is falsy, so check explicitly for undefined/null\n const sheetId = sheet.properties?.sheetId;\n if (sheetId === undefined || sheetId === null) {\n throw new McpError(ErrorCode.InternalError, 'Sheet properties not available');\n }\n\n if (!range) {\n // gid but no range = search specific sheet\n findReplaceRequest.sheetId = sheetId;\n } else {\n // gid + range = search specific range\n const rangeRef = parseA1Notation(range);\n findReplaceRequest.range = rangeReferenceToGridRange(rangeRef, sheetId);\n }\n }\n\n // Execute batchUpdate\n const response = await sheets.spreadsheets.batchUpdate({\n spreadsheetId: id,\n requestBody: {\n requests: [{ findReplace: findReplaceRequest }],\n },\n });\n\n const findReplaceResponse = response.data.replies?.[0]?.findReplace;\n const spreadsheetUrl = `https://docs.google.com/spreadsheets/d/${id}/edit`;\n\n logger.info('sheets.values-replace completed', {\n occurrencesChanged: findReplaceResponse?.occurrencesChanged ?? 0,\n sheetsChanged: findReplaceResponse?.sheetsChanged ?? 0,\n });\n\n const result: Output = {\n type: 'success' as const,\n id,\n spreadsheetUrl,\n occurrencesChanged: findReplaceResponse?.occurrencesChanged ?? 0,\n valuesChanged: findReplaceResponse?.valuesChanged ?? 0,\n formulasChanged: findReplaceResponse?.formulasChanged ?? 0,\n rowsChanged: findReplaceResponse?.rowsChanged ?? 0,\n sheetsChanged: findReplaceResponse?.sheetsChanged ?? 0,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n if (error instanceof McpError) {\n throw error;\n }\n const message = error instanceof Error ? error.message : String(error);\n logger.error('Replace operation failed', {\n id,\n find,\n replacement,\n gid,\n range,\n error: message,\n });\n\n throw new McpError(ErrorCode.InternalError, `Error replacing values: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-replace',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","id","SpreadsheetIdSchema","find","string","min","describe","replacement","gid","SheetGidSchema","optional","range","A1NotationSchema","matchCase","boolean","matchEntireCell","searchByRegex","includeFormulas","refine","data","message","successBranchSchema","type","literal","SpreadsheetIdOutput","spreadsheetUrl","occurrencesChanged","number","int","nonnegative","valuesChanged","formulasChanged","rowsChanged","sheetsChanged","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","response","sheets","findReplaceRequest","spreadsheetResponse","sheet","sheetId","rangeRef","findReplaceResponse","error","info","google","version","auth","authContext","undefined","allSheets","spreadsheets","get","spreadsheetId","fields","s","String","properties","McpError","ErrorCode","InvalidParams","InternalError","parseA1Notation","rangeReferenceToGridRange","batchUpdate","requestBody","requests","findReplace","replies","content","text","JSON","stringify","structuredContent","Error","stack","name"],"mappings":";;;;+BA2JA;;;eAAwBA;;;2BA1JA;qBAMY;0BACG;mBACrB;uBACyE;iCAChC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAR3D,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAUR,IAAME,cAAcC,MAAC,CAClBC,MAAM,CAAC;IACNC,IAAIC,4BAAmB;IACvBC,MAAMJ,MAAC,CAACK,MAAM,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M;QACN/C,QAAAA;QACAG,SAAAA;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-sheets/src/mcp/tools/values-replace.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { CallToolResult, ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { google, type sheets_v4 } from 'googleapis';\nimport { z } from 'zod';\nimport { A1NotationSchema, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\nimport { parseA1Notation, rangeReferenceToGridRange } from '../../spreadsheet/range-operations.ts';\n\nconst inputSchema = z\n .object({\n id: SpreadsheetIdSchema,\n find: z.string().min(1).describe('Text or regex pattern to find'),\n replacement: z.string().describe('Replacement text. Use $1, $2 for regex capture groups. Empty string deletes matches.'),\n\n // Scope - defaults to all sheets if neither specified\n gid: SheetGidSchema.optional().describe('Limit to specific sheet. If omitted, searches all sheets.'),\n range: A1NotationSchema.optional().describe('Limit to specific A1 range within the sheet (requires gid)'),\n\n // Match options\n matchCase: z.boolean().optional().describe('Case-sensitive matching'),\n matchEntireCell: z.boolean().optional().describe('Only match entire cell content'),\n searchByRegex: z.boolean().optional().describe('Treat find as RE2 regex'),\n includeFormulas: z.boolean().optional().describe('Search within formula text'),\n })\n .refine((data) => !(data.range && !data.gid), { message: 'range requires gid' });\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n spreadsheetUrl: z.string().describe('URL of the spreadsheet'),\n occurrencesChanged: z.number().int().nonnegative().describe('Total replacements made'),\n valuesChanged: z.number().int().nonnegative().describe('Number of non-formula cells changed'),\n formulasChanged: z.number().int().nonnegative().describe('Number of formula cells changed'),\n rowsChanged: z.number().int().nonnegative().describe('Number of rows with replacements'),\n sheetsChanged: z.number().int().nonnegative().describe('Number of sheets with replacements'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Find and replace text across a spreadsheet. Searches all sheets by default, or limit with gid/range. Supports regex with capture groups ($1, $2).',\n inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ id, find, replacement, gid, range, matchCase, matchEntireCell, searchByRegex, includeFormulas }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values-replace called', { id, find, replacement, gid, range });\n\n try {\n const sheets = google.sheets({ version: 'v4', auth: extra.authContext.auth });\n\n // Build FindReplaceRequest - only include defined options\n const findReplaceRequest: sheets_v4.Schema$FindReplaceRequest = {\n find,\n replacement,\n ...(matchCase !== undefined && { matchCase }),\n ...(matchEntireCell !== undefined && { matchEntireCell }),\n ...(searchByRegex !== undefined && { searchByRegex }),\n ...(includeFormulas !== undefined && { includeFormulas }),\n };\n\n // Set scope based on gid/range\n if (!gid) {\n // No gid = search all sheets\n findReplaceRequest.allSheets = true;\n } else {\n // Need to resolve sheet to get numeric sheetId\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'sheets.properties.sheetId,sheets.properties.title',\n });\n\n const sheet = spreadsheetResponse.data.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n if (!sheet) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Sheet not found: ${gid}`);\n }\n\n // Note: sheetId can be 0 which is falsy, so check explicitly for undefined/null\n const sheetId = sheet.properties?.sheetId;\n if (sheetId === undefined || sheetId === null) {\n throw new ProtocolError(ProtocolErrorCode.InternalError, 'Sheet properties not available');\n }\n\n if (!range) {\n // gid but no range = search specific sheet\n findReplaceRequest.sheetId = sheetId;\n } else {\n // gid + range = search specific range\n const rangeRef = parseA1Notation(range);\n findReplaceRequest.range = rangeReferenceToGridRange(rangeRef, sheetId);\n }\n }\n\n // Execute batchUpdate\n const response = await sheets.spreadsheets.batchUpdate({\n spreadsheetId: id,\n requestBody: {\n requests: [{ findReplace: findReplaceRequest }],\n },\n });\n\n const findReplaceResponse = response.data.replies?.[0]?.findReplace;\n const spreadsheetUrl = `https://docs.google.com/spreadsheets/d/${id}/edit`;\n\n logger.info('sheets.values-replace completed', {\n occurrencesChanged: findReplaceResponse?.occurrencesChanged ?? 0,\n sheetsChanged: findReplaceResponse?.sheetsChanged ?? 0,\n });\n\n const result: Output = {\n type: 'success' as const,\n id,\n spreadsheetUrl,\n occurrencesChanged: findReplaceResponse?.occurrencesChanged ?? 0,\n valuesChanged: findReplaceResponse?.valuesChanged ?? 0,\n formulasChanged: findReplaceResponse?.formulasChanged ?? 0,\n rowsChanged: findReplaceResponse?.rowsChanged ?? 0,\n sheetsChanged: findReplaceResponse?.sheetsChanged ?? 0,\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n if (error instanceof ProtocolError) {\n throw error;\n }\n const message = error instanceof Error ? error.message : String(error);\n logger.error('Replace operation failed', {\n id,\n find,\n replacement,\n gid,\n range,\n error: message,\n });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error replacing values: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-replace',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","id","SpreadsheetIdSchema","find","string","min","describe","replacement","gid","SheetGidSchema","optional","range","A1NotationSchema","matchCase","boolean","matchEntireCell","searchByRegex","includeFormulas","refine","data","message","successBranchSchema","type","literal","SpreadsheetIdOutput","spreadsheetUrl","occurrencesChanged","number","int","nonnegative","valuesChanged","formulasChanged","rowsChanged","sheetsChanged","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","response","sheets","findReplaceRequest","spreadsheetResponse","sheet","sheetId","rangeRef","findReplaceResponse","error","info","google","version","auth","authContext","undefined","allSheets","spreadsheets","get","spreadsheetId","fields","s","String","properties","ProtocolError","ProtocolErrorCode","InvalidParams","InternalError","parseA1Notation","rangeReferenceToGridRange","batchUpdate","requestBody","requests","findReplace","replies","content","text","JSON","stringify","structuredContent","Error","stack","name"],"mappings":";;;;+BA0JA;;;eAAwBA;;;2BAzJA;sBAKyB;0BACV;mBACrB;uBACyE;iCAChC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAP3D,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AASR,IAAME,cAAcC,MAAC,CAClBC,MAAM,CAAC;IACNC,IAAIC,4BAAmB;IACvBC,MAAMJ,MAAC,CAACK,MAAM,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;IACjCC,aAAaR,MAAC,CAACK,MAAM,GAAGE,QAAQ,CAAC;IAEjC,sDAAsD;IACtDE,KAAKC,uBAAc,CAACC,QAAQ,GAAGJ,QAAQ,CAAC;IACxCK,OAAOC,yBAAgB,CAACF,QAAQ,GAAGJ,QAAQ,CAAC;IAE5C,gBAAgB;IAChBO,WAAWd,MAAC,CAACe,OAAO,GAAGJ,QAAQ,GAAGJ,QAAQ,CAAC;IAC3CS,iBAAiBhB,MAAC,CAACe,OAAO,GAAGJ,QAAQ,GAAGJ,QAAQ,CAAC;IACjDU,eAAejB,MAAC,CAACe,OAAO,GAAGJ,QAAQ,GAAGJ,QAAQ,CAAC;IAC/CW,iBAAiBlB,MAAC,CAACe,OAAO,GAAGJ,QAAQ,GAAGJ,QAAQ,CAAC;AACnD,GACCY,MAAM,CAAC,SAACC;WAAS,CAAEA,CAAAA,KAAK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;wBAAO;4BACL2C,OAAO;gCAAG;oCAAEtD,MAAM;oCAAiBuD,MAAMC,KAAKC,SAAS,CAACzC;gCAAQ;;4BAChE0C,mBAAmB;gCAAE1C,QAAAA;4BAAO;wBAC9B;;;oBACOY;oBACP,IAAIA,AAAK,YAALA,OAAiBe,qBAAa,GAAE;wBAClC,MAAMf;oBACR;oBACM9B,UAAU8B,AAAK,YAALA,OAAiB+B,SAAQ/B,MAAM9B,OAAO,GAAG2C,OAAOb;oBAChET,OAAOS,KAAK,CAAC,4BAA4B;wBACvCjD,IAAAA;wBACAE,MAAAA;wBACAI,aAAAA;wBACAC,KAAAA;wBACAG,OAAAA;wBACAuC,OAAO9B;oBACT;oBAEA,MAAM,IAAI6C,qBAAa,CAACC,yBAAiB,CAACE,aAAa,EAAE,AAAC,2BAAkC,OAARhD,UAAW;wBAC7F8D,OAAOhC,AAAK,YAALA,OAAiB+B,SAAQ/B,MAAMgC,KAAK,GAAG1B;oBAChD;;;;;;;IAEJ;;AAEe,SAAS7D;IACtB,OAAO;QACLwF,MAAM;QACN/C,QAAAA;QACAG,SAAAA;IACF;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { EnrichedExtra } from '@mcp-z/oauth-google';
|
|
2
|
-
import type { CallToolResult } from '@
|
|
2
|
+
import type { CallToolResult } from '@mcp-z/server';
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
declare const inputSchema: z.ZodObject<{
|
|
5
5
|
id: z.ZodString;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { EnrichedExtra } from '@mcp-z/oauth-google';
|
|
2
|
-
import type { CallToolResult } from '@
|
|
2
|
+
import type { CallToolResult } from '@mcp-z/server';
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
declare const inputSchema: z.ZodObject<{
|
|
5
5
|
id: z.ZodString;
|
|
@@ -9,7 +9,7 @@ Object.defineProperty(exports, "default", {
|
|
|
9
9
|
}
|
|
10
10
|
});
|
|
11
11
|
var _oauthgoogle = require("@mcp-z/oauth-google");
|
|
12
|
-
var
|
|
12
|
+
var _server = require("@mcp-z/server");
|
|
13
13
|
var _googleapis = require("googleapis");
|
|
14
14
|
var _zod = require("zod");
|
|
15
15
|
var _indexts = require("../../schemas/index.js");
|
|
@@ -269,7 +269,7 @@ function handler(_0, _1) {
|
|
|
269
269
|
gid: gid,
|
|
270
270
|
query: query
|
|
271
271
|
});
|
|
272
|
-
throw new
|
|
272
|
+
throw new _server.ProtocolError(_server.ProtocolErrorCode.InvalidParams, 'Sheet not found');
|
|
273
273
|
}
|
|
274
274
|
sheetTitle = (_ref = (_sheet_properties = sheet.properties) === null || _sheet_properties === void 0 ? void 0 : _sheet_properties.title) !== null && _ref !== void 0 ? _ref : '';
|
|
275
275
|
// Use actual sheet dimensions from gridProperties, with sensible defaults
|
|
@@ -443,7 +443,7 @@ function handler(_0, _1) {
|
|
|
443
443
|
logger.error('sheets.values-search error', {
|
|
444
444
|
error: message
|
|
445
445
|
});
|
|
446
|
-
throw new
|
|
446
|
+
throw new _server.ProtocolError(_server.ProtocolErrorCode.InternalError, "Error searching spreadsheet: ".concat(message), {
|
|
447
447
|
stack: _instanceof(error, Error) ? error.stack : undefined
|
|
448
448
|
});
|
|
449
449
|
case 5:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-sheets/src/mcp/tools/values-search.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { ToolModule } from '@mcp-z/server';\nimport type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';\nimport { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\nimport { SheetCellSchema, SheetGidSchema, SpreadsheetIdSchema } from '../../schemas/index.ts';\n\n// Helper to convert column index to letter (0 = A, 1 = B, etc.)\nfunction columnIndexToLetter(index: number): string {\n let letter = '';\n let num = index + 1;\n while (num > 0) {\n const remainder = (num - 1) % 26;\n letter = String.fromCharCode(65 + remainder) + letter;\n num = Math.floor((num - 1) / 26);\n }\n return letter;\n}\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n query: z.coerce.string().trim().optional().describe('Text to search for in sheet cells. If empty, returns all data at specified granularity.'),\n select: z.enum(['cells', 'rows', 'columns']).describe('Granularity: cells (individual matches), rows (full matching rows), columns (columns with matching headers)'),\n values: z.boolean().optional().describe('Include cell values in response'),\n a1s: z.boolean().optional().describe('Include A1 notation references in response'),\n render: z.enum(['FORMATTED_VALUE', 'UNFORMATTED_VALUE', 'FORMULA']).optional().describe('How to render cell values. FORMATTED_VALUE (default): calculated with formatting. UNFORMATTED_VALUE: calculated without formatting. FORMULA: show formula text instead of result.'),\n matchCase: z.boolean().optional().describe('Case-sensitive matching. Default is false (case-insensitive).'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n count: z.number().int().nonnegative().describe('Number of matches found'),\n a1s: z.array(z.string()).optional().describe('A1 notation references for matches (e.g., \"B5\", \"A5:D5\", \"B:B\")'),\n values: z\n .array(z.union([z.array(SheetCellSchema), SheetCellSchema]))\n .optional()\n .describe('Cell values for matches (arrays for rows/columns, single values for cells)'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Search spreadsheet and return matches at cell, row, or column granularity. Use a1-notation prompt for range syntax.',\n inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ id, gid, query, select, values = false, a1s = false, render, matchCase = false }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values-search called', { id, gid, query, select, values, a1s, render, matchCase });\n\n try {\n const sheets = google.sheets({ version: 'v4', auth: extra.authContext.auth });\n\n // Get sheet details including grid dimensions\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'sheets.properties.sheetId,sheets.properties.title,sheets.properties.gridProperties',\n });\n\n const sheet = spreadsheetResponse.data.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n\n if (!sheet) {\n logger.info('sheets.values-search sheet not found', { id, gid, query });\n throw new McpError(ErrorCode.InvalidParams, 'Sheet not found');\n }\n\n const sheetTitle = sheet.properties?.title ?? '';\n\n // Use actual sheet dimensions from gridProperties, with sensible defaults\n // Google Sheets default for new sheets is 1000 rows x 26 columns\n const rowCount = sheet.properties?.gridProperties?.rowCount ?? 1000;\n const columnCount = sheet.properties?.gridProperties?.columnCount ?? 26;\n const endColumn = columnIndexToLetter(columnCount - 1);\n const fullRange = `${sheetTitle}!A1:${endColumn}${rowCount}`;\n\n logger.debug?.('sheets.values-search fetching range', { fullRange, rowCount, columnCount });\n\n const response = await sheets.spreadsheets.values.get({\n spreadsheetId: id,\n range: fullRange,\n valueRenderOption: render || 'FORMATTED_VALUE',\n });\n const res = response.data;\n const allRows = Array.isArray(res.values) ? (res.values as (string | number | boolean | null)[][]) : [];\n\n // Prepare query for matching (case-insensitive by default)\n const searchQuery = query ? (matchCase ? query : query.toLowerCase()) : null;\n\n let count = 0;\n const a1Array: string[] = [];\n const valuesArray: (string | number | boolean | null | (string | number | boolean | null)[])[] = [];\n\n // Helper to check if a cell matches the query\n const cellMatches = (cell: string | number | boolean | null): boolean => {\n if (!searchQuery) return true; // If no query, match all\n if (typeof cell !== 'string') return false;\n const cellValue = matchCase ? cell : cell.toLowerCase();\n return cellValue.includes(searchQuery);\n };\n\n if (select === 'cells') {\n for (let rowIdx = 0; rowIdx < allRows.length; rowIdx++) {\n const row = allRows[rowIdx];\n if (!row) continue;\n\n for (let colIdx = 0; colIdx < row.length; colIdx++) {\n const cell = row[colIdx];\n if (cellMatches(cell)) {\n count++;\n if (a1s) {\n const colLetter = columnIndexToLetter(colIdx);\n const rowNum = rowIdx + 1;\n a1Array.push(`${colLetter}${rowNum}`);\n }\n if (values) {\n valuesArray.push(cell ?? null);\n }\n }\n }\n }\n } else if (select === 'rows') {\n const matchingRows: number[] = [];\n for (let rowIdx = 0; rowIdx < allRows.length; rowIdx++) {\n const row = allRows[rowIdx];\n if (!row) continue;\n\n const matches = row.some((cell) => cellMatches(cell));\n if (matches) {\n matchingRows.push(rowIdx);\n }\n }\n\n count = matchingRows.length;\n for (const rowIdx of matchingRows) {\n const row = allRows[rowIdx];\n if (!row) continue; // Skip if row is undefined\n const rowNum = rowIdx + 1;\n\n if (a1s) {\n const colEnd = columnIndexToLetter(Math.max(0, row.length - 1));\n a1Array.push(`A${rowNum}:${colEnd}${rowNum}`);\n }\n if (values) {\n valuesArray.push(row);\n }\n }\n } else if (select === 'columns') {\n const headerRow = allRows[0] || [];\n const matchingCols: number[] = [];\n\n for (let colIdx = 0; colIdx < headerRow.length; colIdx++) {\n const header = headerRow[colIdx];\n if (cellMatches(header)) {\n matchingCols.push(colIdx);\n }\n }\n\n count = matchingCols.length;\n for (const colIdx of matchingCols) {\n const colLetter = columnIndexToLetter(colIdx);\n\n if (a1s) {\n a1Array.push(`${colLetter}:${colLetter}`);\n }\n if (values) {\n const columnValues = allRows.map((row) => (row && row[colIdx] !== undefined ? row[colIdx] : null));\n valuesArray.push(columnValues);\n }\n }\n }\n\n logger.info('sheets.values-search results', { count, select, hasA1s: a1s, hasValues: values });\n\n const result: Output = {\n type: 'success' as const,\n count,\n ...(a1s && a1Array.length > 0 && { a1s: a1Array }),\n ...(values && valuesArray.length > 0 && { values: valuesArray }),\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('sheets.values-search error', { error: message });\n\n throw new McpError(ErrorCode.InternalError, `Error searching spreadsheet: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-search',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","columnIndexToLetter","index","letter","num","remainder","String","fromCharCode","Math","floor","inputSchema","z","object","id","SpreadsheetIdSchema","gid","SheetGidSchema","query","coerce","string","trim","optional","describe","select","enum","values","boolean","a1s","render","matchCase","successBranchSchema","type","literal","count","number","int","nonnegative","array","union","SheetCellSchema","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","spreadsheetResponse","sheet","sheets","sheetTitle","rowCount","columnCount","endColumn","fullRange","response","res","allRows","searchQuery","a1Array","valuesArray","cellMatches","rowIdx","row","colIdx","cell","colLetter","rowNum","matchingRows","matches","colEnd","headerRow","matchingCols","header","error","message","info","google","version","auth","authContext","spreadsheets","get","spreadsheetId","fields","data","find","s","properties","sheetId","McpError","ErrorCode","InvalidParams","title","gridProperties","debug","range","valueRenderOption","Array","isArray","toLowerCase","cellValue","includes","length","push","some","max","columnValues","map","undefined","hasA1s","hasValues","content","text","JSON","stringify","structuredContent","Error","InternalError","stack","name"],"mappings":";;;;+BA8MA;;;eAAwBA;;;2BA7MA;qBAMY;0BACb;mBACL;uBACmD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAPrE,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AASR,gEAAgE;AAChE,SAASE,oBAAoBC,KAAa;IACxC,IAAIC,SAAS;IACb,IAAIC,MAAMF,QAAQ;IAClB,MAAOE,MAAM,EAAG;QACd,IAAMC,YAAY,AAACD,CAAAA,MAAM,CAAA,IAAK;QAC9BD,SAASG,OAAOC,YAAY,CAAC,KAAKF,aAAaF;QAC/CC,MAAMI,KAAK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BAAE5C,OAAAA;wBAAOV,QAAAA;wBAAQwF,QAAQpF;wBAAKqF,WAAWvF;oBAAO;oBAEtFmB,SAAiB;wBACrBb,MAAM;wBACNE,OAAAA;uBACIN,OAAOiC,QAAQ4C,MAAM,GAAG,KAAK;wBAAE7E,KAAKiC;oBAAQ,GAC5CnC,UAAUoC,YAAY2C,MAAM,GAAG,KAAK;wBAAE/E,QAAQoC;oBAAY;oBAGhE;;wBAAO;4BACLoD,OAAO;gCAAG;oCAAElF,MAAM;oCAAiBmF,MAAMC,KAAKC,SAAS,CAACxE;gCAAQ;;4BAChEyE,mBAAmB;gCAAEzE,QAAAA;4BAAO;wBAC9B;;;oBACO+B;oBACDC,UAAUD,AAAK,YAALA,OAAiB2C,SAAQ3C,MAAMC,OAAO,GAAGtE,OAAOqE;oBAChE5B,OAAO4B,KAAK,CAAC,8BAA8B;wBAAEA,OAAOC;oBAAQ;oBAE5D,MAAM,IAAIe,eAAQ,CAACC,gBAAS,CAAC2B,aAAa,EAAE,AAAC,gCAAuC,OAAR3C,UAAW;wBACrF4C,OAAO7C,AAAK,YAALA,OAAiB2C,SAAQ3C,MAAM6C,KAAK,GAAGV;oBAChD;;;;;;;IAEJ;;AAEe,SAAShH;IACtB,OAAO;QACL2H,MAAM;QACN/E,QAAAA;QACAG,SAAAA;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-sheets/src/mcp/tools/values-search.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { CallToolResult, ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\nimport { SheetCellSchema, SheetGidSchema, SpreadsheetIdSchema } from '../../schemas/index.ts';\n\n// Helper to convert column index to letter (0 = A, 1 = B, etc.)\nfunction columnIndexToLetter(index: number): string {\n let letter = '';\n let num = index + 1;\n while (num > 0) {\n const remainder = (num - 1) % 26;\n letter = String.fromCharCode(65 + remainder) + letter;\n num = Math.floor((num - 1) / 26);\n }\n return letter;\n}\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n query: z.coerce.string().trim().optional().describe('Text to search for in sheet cells. If empty, returns all data at specified granularity.'),\n select: z.enum(['cells', 'rows', 'columns']).describe('Granularity: cells (individual matches), rows (full matching rows), columns (columns with matching headers)'),\n values: z.boolean().optional().describe('Include cell values in response'),\n a1s: z.boolean().optional().describe('Include A1 notation references in response'),\n render: z.enum(['FORMATTED_VALUE', 'UNFORMATTED_VALUE', 'FORMULA']).optional().describe('How to render cell values. FORMATTED_VALUE (default): calculated with formatting. UNFORMATTED_VALUE: calculated without formatting. FORMULA: show formula text instead of result.'),\n matchCase: z.boolean().optional().describe('Case-sensitive matching. Default is false (case-insensitive).'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n count: z.number().int().nonnegative().describe('Number of matches found'),\n a1s: z.array(z.string()).optional().describe('A1 notation references for matches (e.g., \"B5\", \"A5:D5\", \"B:B\")'),\n values: z\n .array(z.union([z.array(SheetCellSchema), SheetCellSchema]))\n .optional()\n .describe('Cell values for matches (arrays for rows/columns, single values for cells)'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Search spreadsheet and return matches at cell, row, or column granularity. Use a1-notation prompt for range syntax.',\n inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ id, gid, query, select, values = false, a1s = false, render, matchCase = false }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values-search called', { id, gid, query, select, values, a1s, render, matchCase });\n\n try {\n const sheets = google.sheets({ version: 'v4', auth: extra.authContext.auth });\n\n // Get sheet details including grid dimensions\n const spreadsheetResponse = await sheets.spreadsheets.get({\n spreadsheetId: id,\n fields: 'sheets.properties.sheetId,sheets.properties.title,sheets.properties.gridProperties',\n });\n\n const sheet = spreadsheetResponse.data.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n\n if (!sheet) {\n logger.info('sheets.values-search sheet not found', { id, gid, query });\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Sheet not found');\n }\n\n const sheetTitle = sheet.properties?.title ?? '';\n\n // Use actual sheet dimensions from gridProperties, with sensible defaults\n // Google Sheets default for new sheets is 1000 rows x 26 columns\n const rowCount = sheet.properties?.gridProperties?.rowCount ?? 1000;\n const columnCount = sheet.properties?.gridProperties?.columnCount ?? 26;\n const endColumn = columnIndexToLetter(columnCount - 1);\n const fullRange = `${sheetTitle}!A1:${endColumn}${rowCount}`;\n\n logger.debug?.('sheets.values-search fetching range', { fullRange, rowCount, columnCount });\n\n const response = await sheets.spreadsheets.values.get({\n spreadsheetId: id,\n range: fullRange,\n valueRenderOption: render || 'FORMATTED_VALUE',\n });\n const res = response.data;\n const allRows = Array.isArray(res.values) ? (res.values as (string | number | boolean | null)[][]) : [];\n\n // Prepare query for matching (case-insensitive by default)\n const searchQuery = query ? (matchCase ? query : query.toLowerCase()) : null;\n\n let count = 0;\n const a1Array: string[] = [];\n const valuesArray: (string | number | boolean | null | (string | number | boolean | null)[])[] = [];\n\n // Helper to check if a cell matches the query\n const cellMatches = (cell: string | number | boolean | null): boolean => {\n if (!searchQuery) return true; // If no query, match all\n if (typeof cell !== 'string') return false;\n const cellValue = matchCase ? cell : cell.toLowerCase();\n return cellValue.includes(searchQuery);\n };\n\n if (select === 'cells') {\n for (let rowIdx = 0; rowIdx < allRows.length; rowIdx++) {\n const row = allRows[rowIdx];\n if (!row) continue;\n\n for (let colIdx = 0; colIdx < row.length; colIdx++) {\n const cell = row[colIdx];\n if (cellMatches(cell)) {\n count++;\n if (a1s) {\n const colLetter = columnIndexToLetter(colIdx);\n const rowNum = rowIdx + 1;\n a1Array.push(`${colLetter}${rowNum}`);\n }\n if (values) {\n valuesArray.push(cell ?? null);\n }\n }\n }\n }\n } else if (select === 'rows') {\n const matchingRows: number[] = [];\n for (let rowIdx = 0; rowIdx < allRows.length; rowIdx++) {\n const row = allRows[rowIdx];\n if (!row) continue;\n\n const matches = row.some((cell) => cellMatches(cell));\n if (matches) {\n matchingRows.push(rowIdx);\n }\n }\n\n count = matchingRows.length;\n for (const rowIdx of matchingRows) {\n const row = allRows[rowIdx];\n if (!row) continue; // Skip if row is undefined\n const rowNum = rowIdx + 1;\n\n if (a1s) {\n const colEnd = columnIndexToLetter(Math.max(0, row.length - 1));\n a1Array.push(`A${rowNum}:${colEnd}${rowNum}`);\n }\n if (values) {\n valuesArray.push(row);\n }\n }\n } else if (select === 'columns') {\n const headerRow = allRows[0] || [];\n const matchingCols: number[] = [];\n\n for (let colIdx = 0; colIdx < headerRow.length; colIdx++) {\n const header = headerRow[colIdx];\n if (cellMatches(header)) {\n matchingCols.push(colIdx);\n }\n }\n\n count = matchingCols.length;\n for (const colIdx of matchingCols) {\n const colLetter = columnIndexToLetter(colIdx);\n\n if (a1s) {\n a1Array.push(`${colLetter}:${colLetter}`);\n }\n if (values) {\n const columnValues = allRows.map((row) => (row && row[colIdx] !== undefined ? row[colIdx] : null));\n valuesArray.push(columnValues);\n }\n }\n }\n\n logger.info('sheets.values-search results', { count, select, hasA1s: a1s, hasValues: values });\n\n const result: Output = {\n type: 'success' as const,\n count,\n ...(a1s && a1Array.length > 0 && { a1s: a1Array }),\n ...(values && valuesArray.length > 0 && { values: valuesArray }),\n };\n\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result) }],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('sheets.values-search error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error searching spreadsheet: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-search',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","columnIndexToLetter","index","letter","num","remainder","String","fromCharCode","Math","floor","inputSchema","z","object","id","SpreadsheetIdSchema","gid","SheetGidSchema","query","coerce","string","trim","optional","describe","select","enum","values","boolean","a1s","render","matchCase","successBranchSchema","type","literal","count","number","int","nonnegative","array","union","SheetCellSchema","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","spreadsheetResponse","sheet","sheets","sheetTitle","rowCount","columnCount","endColumn","fullRange","response","res","allRows","searchQuery","a1Array","valuesArray","cellMatches","rowIdx","row","colIdx","cell","colLetter","rowNum","matchingRows","matches","colEnd","headerRow","matchingCols","header","error","message","info","google","version","auth","authContext","spreadsheets","get","spreadsheetId","fields","data","find","s","properties","sheetId","ProtocolError","ProtocolErrorCode","InvalidParams","title","gridProperties","debug","range","valueRenderOption","Array","isArray","toLowerCase","cellValue","includes","length","push","some","max","columnValues","map","undefined","hasA1s","hasValues","content","text","JSON","stringify","structuredContent","Error","InternalError","stack","name"],"mappings":";;;;+BA6MA;;;eAAwBA;;;2BA5MA;sBAKyB;0BAC1B;mBACL;uBACmD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AANrE,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAQR,gEAAgE;AAChE,SAASE,oBAAoBC,KAAa;IACxC,IAAIC,SAAS;IACb,IAAIC,MAAMF,QAAQ;IAClB,MAAOE,MAAM,EAAG;QACd,IAAMC,YAAY,AAACD,CAAAA,MAAM,CAAA,IAAK;QAC9BD,SAASG,OAAOC,YAAY,CAAC,KAAKF,aAAaF;QAC/C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CAAC,gCAAgC;wBAAE5C,OAAAA;wBAAOV,QAAAA;wBAAQwF,QAAQpF;wBAAKqF,WAAWvF;oBAAO;oBAEtFmB,SAAiB;wBACrBb,MAAM;wBACNE,OAAAA;uBACIN,OAAOiC,QAAQ4C,MAAM,GAAG,KAAK;wBAAE7E,KAAKiC;oBAAQ,GAC5CnC,UAAUoC,YAAY2C,MAAM,GAAG,KAAK;wBAAE/E,QAAQoC;oBAAY;oBAGhE;;wBAAO;4BACLoD,OAAO;gCAAG;oCAAElF,MAAM;oCAAiBmF,MAAMC,KAAKC,SAAS,CAACxE;gCAAQ;;4BAChEyE,mBAAmB;gCAAEzE,QAAAA;4BAAO;wBAC9B;;;oBACO+B;oBACDC,UAAUD,AAAK,YAALA,OAAiB2C,SAAQ3C,MAAMC,OAAO,GAAGtE,OAAOqE;oBAChE5B,OAAO4B,KAAK,CAAC,8BAA8B;wBAAEA,OAAOC;oBAAQ;oBAE5D,MAAM,IAAIe,qBAAa,CAACC,yBAAiB,CAAC2B,aAAa,EAAE,AAAC,gCAAuC,OAAR3C,UAAW;wBAClG4C,OAAO7C,AAAK,YAALA,OAAiB2C,SAAQ3C,MAAM6C,KAAK,GAAGV;oBAChD;;;;;;;IAEJ;;AAEe,SAAShH;IACtB,OAAO;QACL2H,MAAM;QACN/E,QAAAA;QACAG,SAAAA;IACF;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { McpServer } from '@
|
|
1
|
+
import { McpServer } from '@mcp-z/server';
|
|
2
2
|
import type { RuntimeOverrides, ServerConfig } from '../types.js';
|
|
3
3
|
export declare function createHTTPServer(config: ServerConfig, overrides?: RuntimeOverrides): Promise<{
|
|
4
4
|
httpServer: import("node:http").Server<typeof import("node:http").IncomingMessage, typeof import("node:http").ServerResponse>;
|
package/dist/cjs/setup/http.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { McpServer } from '@
|
|
1
|
+
import { McpServer } from '@mcp-z/server';
|
|
2
2
|
import type { RuntimeOverrides, ServerConfig } from '../types.js';
|
|
3
3
|
export declare function createHTTPServer(config: ServerConfig, overrides?: RuntimeOverrides): Promise<{
|
|
4
4
|
httpServer: import("node:http").Server<typeof import("node:http").IncomingMessage, typeof import("node:http").ServerResponse>;
|
package/dist/cjs/setup/http.js
CHANGED
|
@@ -9,7 +9,6 @@ Object.defineProperty(exports, "createHTTPServer", {
|
|
|
9
9
|
}
|
|
10
10
|
});
|
|
11
11
|
var _server = require("@mcp-z/server");
|
|
12
|
-
var _mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
|
|
13
12
|
var _cors = /*#__PURE__*/ _interop_require_default(require("cors"));
|
|
14
13
|
var _express = /*#__PURE__*/ _interop_require_default(require("express"));
|
|
15
14
|
var _runtimets = require("./runtime.js");
|
|
@@ -172,7 +171,7 @@ function _unsupported_iterable_to_array(o, minLen) {
|
|
|
172
171
|
}
|
|
173
172
|
function createHTTPServer(config, overrides) {
|
|
174
173
|
return _async_to_generator(function() {
|
|
175
|
-
var runtime, modules, layers, composed, logger, port, tools, prompts, mcpServer, app, _ref, close, httpServer;
|
|
174
|
+
var runtime, modules, layers, composed, logger, port, tools, prompts, mcpServer, app, publicUrl, _ref, close, httpServer;
|
|
176
175
|
return _ts_generator(this, function(_state) {
|
|
177
176
|
switch(_state.label){
|
|
178
177
|
case 0:
|
|
@@ -192,7 +191,7 @@ function createHTTPServer(config, overrides) {
|
|
|
192
191
|
if (!port) throw new Error('Port is required for HTTP transport');
|
|
193
192
|
tools = _to_consumable_array(composed.tools).concat(_to_consumable_array(runtime.deps.oauthAdapters.accountTools));
|
|
194
193
|
prompts = _to_consumable_array(composed.prompts).concat(_to_consumable_array(runtime.deps.oauthAdapters.accountPrompts));
|
|
195
|
-
mcpServer = new
|
|
194
|
+
mcpServer = new _server.McpServer({
|
|
196
195
|
name: config.name,
|
|
197
196
|
version: config.version
|
|
198
197
|
});
|
|
@@ -200,29 +199,40 @@ function createHTTPServer(config, overrides) {
|
|
|
200
199
|
(0, _server.registerResources)(mcpServer, composed.resources);
|
|
201
200
|
(0, _server.registerPrompts)(mcpServer, prompts);
|
|
202
201
|
app = (0, _express.default)();
|
|
203
|
-
app.use((0, _cors.default)());
|
|
204
202
|
app.use(_express.default.json({
|
|
205
203
|
limit: '10mb'
|
|
206
204
|
}));
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
}
|
|
211
|
-
if (runtime.deps.oauthAdapters.dcrRouter) {
|
|
212
|
-
app.use('/', runtime.deps.oauthAdapters.dcrRouter);
|
|
213
|
-
logger.info('Mounted DCR router with OAuth endpoints');
|
|
214
|
-
}
|
|
205
|
+
// Must mount '/mcp' before any permissive app-level cors(), or that layer answers its
|
|
206
|
+
// preflight first; pass baseUrl's origin/host below or a public deployment 403s itself.
|
|
207
|
+
publicUrl = config.baseUrl ? new URL(config.baseUrl) : undefined;
|
|
215
208
|
logger.info("Starting ".concat(config.name, " MCP server (http)"));
|
|
216
209
|
return [
|
|
217
210
|
4,
|
|
218
211
|
(0, _server.connectHttp)(mcpServer, {
|
|
219
212
|
logger: logger,
|
|
220
213
|
app: app,
|
|
221
|
-
port: port
|
|
214
|
+
port: port,
|
|
215
|
+
allowedOrigins: publicUrl ? [
|
|
216
|
+
publicUrl.origin
|
|
217
|
+
] : undefined,
|
|
218
|
+
allowedHosts: publicUrl ? [
|
|
219
|
+
publicUrl.host
|
|
220
|
+
] : undefined
|
|
222
221
|
})
|
|
223
222
|
];
|
|
224
223
|
case 2:
|
|
225
224
|
_ref = _state.sent(), close = _ref.close, httpServer = _ref.httpServer;
|
|
225
|
+
// The loopback OAuth callback and the DCR discovery/registration endpoints are
|
|
226
|
+
// meant to be reached from a browser on another origin. Keep cors() for them,
|
|
227
|
+
// scoped to their own routes - never in front of '/mcp'.
|
|
228
|
+
if (runtime.deps.oauthAdapters.loopbackRouter) {
|
|
229
|
+
app.use('/', (0, _cors.default)(), runtime.deps.oauthAdapters.loopbackRouter);
|
|
230
|
+
logger.info('Mounted loopback OAuth callback router');
|
|
231
|
+
}
|
|
232
|
+
if (runtime.deps.oauthAdapters.dcrRouter) {
|
|
233
|
+
app.use('/', (0, _cors.default)(), runtime.deps.oauthAdapters.dcrRouter);
|
|
234
|
+
logger.info('Mounted DCR router with OAuth endpoints');
|
|
235
|
+
}
|
|
226
236
|
logger.info('http transport ready');
|
|
227
237
|
return [
|
|
228
238
|
2,
|