@mcp-z/mcp-sheets 2.5.0 → 2.6.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 +1 -1
- package/dist/cjs/constants.d.cts +24 -0
- package/dist/cjs/constants.d.ts +24 -0
- package/dist/cjs/constants.js +56 -0
- package/dist/cjs/constants.js.map +1 -1
- package/dist/cjs/lib/create-store.d.cts +2 -1
- package/dist/cjs/lib/create-store.d.ts +2 -1
- package/dist/cjs/lib/create-store.js +82 -7
- package/dist/cjs/lib/create-store.js.map +1 -1
- package/dist/cjs/mcp/tools/cells-format.d.cts +3 -3
- package/dist/cjs/mcp/tools/cells-format.d.ts +3 -3
- package/dist/cjs/mcp/tools/cells-format.js +3 -2
- package/dist/cjs/mcp/tools/cells-format.js.map +1 -1
- package/dist/cjs/mcp/tools/columns-get.d.cts +2 -2
- package/dist/cjs/mcp/tools/columns-get.d.ts +2 -2
- package/dist/cjs/mcp/tools/columns-get.js +2 -1
- 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 +3 -2
- package/dist/cjs/mcp/tools/columns-update.js.map +1 -1
- package/dist/cjs/mcp/tools/csv-get-columns.js +1 -1
- package/dist/cjs/mcp/tools/lib/dimension-operations.js +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 +2 -1
- 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 +3 -2
- package/dist/cjs/mcp/tools/rows-csv-append.js.map +1 -1
- package/dist/cjs/mcp/tools/rows-get.d.cts +2 -2
- package/dist/cjs/mcp/tools/rows-get.d.ts +2 -2
- package/dist/cjs/mcp/tools/rows-get.js +2 -1
- package/dist/cjs/mcp/tools/rows-get.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 +3 -2
- package/dist/cjs/mcp/tools/values-batch-update.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 +3 -2
- package/dist/cjs/mcp/tools/values-csv-update.js.map +1 -1
- package/dist/cjs/mcp/tools/values-search.d.cts +2 -2
- package/dist/cjs/mcp/tools/values-search.d.ts +2 -2
- package/dist/cjs/mcp/tools/values-search.js +2 -1
- package/dist/cjs/mcp/tools/values-search.js.map +1 -1
- package/dist/cjs/setup/http.js +1 -1
- package/dist/cjs/setup/runtime.d.cts +2 -2
- package/dist/cjs/setup/runtime.d.ts +2 -2
- package/dist/cjs/setup/runtime.js +6 -6
- package/dist/cjs/setup/runtime.js.map +1 -1
- package/dist/cjs/setup/stdio.js +1 -1
- package/dist/cjs/spreadsheet/data-operations.js +2 -18
- package/dist/cjs/spreadsheet/data-operations.js.map +1 -1
- package/dist/cjs/spreadsheet/markdown-runs.js +1 -1
- package/dist/cjs/spreadsheet/range-operations.d.cts +1 -5
- package/dist/cjs/spreadsheet/range-operations.d.ts +1 -5
- package/dist/cjs/spreadsheet/range-operations.js +1 -29
- package/dist/cjs/spreadsheet/range-operations.js.map +1 -1
- package/dist/cjs/spreadsheet/sheet-operations.js +25 -75
- package/dist/cjs/spreadsheet/sheet-operations.js.map +1 -1
- package/dist/esm/constants.d.ts +24 -0
- package/dist/esm/constants.js +41 -0
- package/dist/esm/constants.js.map +1 -1
- package/dist/esm/lib/create-store.d.ts +2 -1
- package/dist/esm/lib/create-store.js +22 -4
- package/dist/esm/lib/create-store.js.map +1 -1
- package/dist/esm/mcp/tools/cells-format.d.ts +3 -3
- package/dist/esm/mcp/tools/cells-format.js +3 -2
- package/dist/esm/mcp/tools/cells-format.js.map +1 -1
- package/dist/esm/mcp/tools/columns-get.d.ts +2 -2
- package/dist/esm/mcp/tools/columns-get.js +2 -1
- 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 +3 -2
- package/dist/esm/mcp/tools/columns-update.js.map +1 -1
- package/dist/esm/mcp/tools/rows-append.d.ts +1 -1
- package/dist/esm/mcp/tools/rows-append.js +2 -1
- 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 +2 -1
- package/dist/esm/mcp/tools/rows-csv-append.js.map +1 -1
- package/dist/esm/mcp/tools/rows-get.d.ts +2 -2
- package/dist/esm/mcp/tools/rows-get.js +2 -1
- package/dist/esm/mcp/tools/rows-get.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 +3 -2
- package/dist/esm/mcp/tools/values-batch-update.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 +3 -2
- package/dist/esm/mcp/tools/values-csv-update.js.map +1 -1
- package/dist/esm/mcp/tools/values-search.d.ts +2 -2
- package/dist/esm/mcp/tools/values-search.js +2 -1
- package/dist/esm/mcp/tools/values-search.js.map +1 -1
- package/dist/esm/setup/runtime.d.ts +2 -2
- package/dist/esm/setup/runtime.js +6 -6
- package/dist/esm/setup/runtime.js.map +1 -1
- package/dist/esm/spreadsheet/data-operations.js +7 -11
- package/dist/esm/spreadsheet/data-operations.js.map +1 -1
- package/dist/esm/spreadsheet/range-operations.d.ts +1 -5
- package/dist/esm/spreadsheet/range-operations.js +0 -27
- package/dist/esm/spreadsheet/range-operations.js.map +1 -1
- package/dist/esm/spreadsheet/sheet-operations.js +19 -36
- package/dist/esm/spreadsheet/sheet-operations.js.map +1 -1
- package/package.json +7 -7
|
@@ -12,6 +12,7 @@ var _sheets = require("@googleapis/sheets");
|
|
|
12
12
|
var _oauthgoogle = require("@mcp-z/oauth-google");
|
|
13
13
|
var _server = require("@mcp-z/server");
|
|
14
14
|
var _zod = require("zod");
|
|
15
|
+
var _constantsts = require("../../constants.js");
|
|
15
16
|
var _googleauthts = require("../../lib/google-auth.js");
|
|
16
17
|
var _indexts = require("../../schemas/index.js");
|
|
17
18
|
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
|
|
@@ -162,7 +163,7 @@ var inputSchema = _zod.z.object({
|
|
|
162
163
|
valueInputOption: _zod.z.enum([
|
|
163
164
|
'RAW',
|
|
164
165
|
'USER_ENTERED'
|
|
165
|
-
]).describe('How input data should be interpreted (RAW = exact values, USER_ENTERED = parsed like user input
|
|
166
|
+
]).describe('How input data should be interpreted (required; no default is applied by the schema). RAW = exact values: date strings stay text, numeric serials stay numbers. USER_ENTERED = parsed like user input: date strings may become native dates per the workbook locale.'),
|
|
166
167
|
includeData: _zod.z.boolean().describe('Whether to include updated cell values in the response')
|
|
167
168
|
});
|
|
168
169
|
var successBranchSchema = _zod.z.object({
|
|
@@ -191,7 +192,7 @@ var outputSchema = _zod.z.discriminatedUnion('type', [
|
|
|
191
192
|
AuthRequiredBranchSchema
|
|
192
193
|
]);
|
|
193
194
|
var config = {
|
|
194
|
-
description:
|
|
195
|
+
description: "Batch update multiple cell ranges. RAW=exact values, USER_ENTERED=parsed like user input. Use a1-notation prompt for range syntax. For multiple clickable links or rich text inside a single cell, use values-markdown-update. ".concat(_constantsts.NATIVE_DATE_GUIDANCE),
|
|
195
196
|
inputSchema: inputSchema,
|
|
196
197
|
outputSchema: _zod.z.object({
|
|
197
198
|
result: outputSchema
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/mcp/tools/values-batch-update.ts"],"sourcesContent":["import { sheets as sheetsApi } from '@googleapis/sheets';\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 { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { A1NotationSchema, SheetCellSchema, SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\n\n// Types for updated data response\ninterface UpdatedDataItem {\n range: string;\n majorDimension: 'ROWS' | 'COLUMNS';\n values?: (string | number | boolean | null)[][];\n}\n\n// Input schema for values batch update requests\nconst ValuesBatchUpdateRequestSchema = z.object({\n range: A1NotationSchema.describe('A1 notation range defining the bounded target area. Data dimensions must match range dimensions. Example: D1:D100 requires exactly 100 rows of data. Use open-ended ranges like D1:D to write any number of rows.'),\n values: z.array(z.array(SheetCellSchema)).min(1).describe('2D array of values. Row count must match range height, column count must match range width. Use null to skip a cell (preserve existing value), empty string \"\" to clear it.'),\n majorDimension: z.enum(['ROWS', 'COLUMNS']).describe('Whether values represent rows or columns'),\n});\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n requests: z.array(ValuesBatchUpdateRequestSchema).min(1).describe('Array of value update requests'),\n valueInputOption: z.enum(['RAW', 'USER_ENTERED']).describe('How input data should be interpreted (RAW = exact values, USER_ENTERED = parsed like user input)'),\n includeData: z.boolean().describe('Whether to include updated cell values in the response'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n gid: SheetGidOutput,\n spreadsheetTitle: z.string().describe('Title of the updated spreadsheet'),\n spreadsheetUrl: z.string().describe('URL of the updated spreadsheet'),\n sheetTitle: z.string().describe('Title of the updated sheet'),\n sheetUrl: z.string().describe('URL of the updated sheet'),\n totalUpdatedRows: z.number().int().nonnegative().describe('Total number of rows updated across all requests'),\n totalUpdatedColumns: z.number().int().nonnegative().describe('Total number of columns updated across all requests'),\n totalUpdatedCells: z.number().int().nonnegative().describe('Total number of cells updated across all requests'),\n updatedRanges: z.array(z.string()).describe('A1 notation ranges that were updated'),\n updatedData: z\n .array(\n z.object({\n range: z.string().describe('A1 notation range that was updated'),\n majorDimension: z.enum(['ROWS', 'COLUMNS']).describe('Dimension of the updated data'),\n values: z.array(z.array(SheetCellSchema)).optional().describe('Updated values (if includeData was true)'),\n })\n )\n .optional()\n .describe('Detailed information about updated data (if includeData was true)'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Batch update multiple cell ranges. RAW=exact values, USER_ENTERED=parsed like user input. Use a1-notation prompt for range syntax. For multiple clickable links or rich text inside a single cell, use values-markdown-update.',\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, valueInputOption = 'USER_ENTERED', includeData = false }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values.batchUpdate called', {\n id,\n gid,\n requestCount: requests.length,\n valueInputOption,\n includeData,\n });\n\n try {\n const sheets = sheetsApi({ version: 'v4', auth: googleAuth(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 const spreadsheetTitle = spreadsheetData.properties?.title ?? '';\n const spreadsheetUrl = spreadsheetData.spreadsheetUrl ?? '';\n\n // Find sheet by gid\n const sheet = spreadsheetData.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n if (!sheet?.properties) {\n logger.info('Sheet not found for batch 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 const sheetGid = sheet.properties.sheetId ?? 0;\n const sheetUrl = `https://docs.google.com/spreadsheets/d/${id}/edit#gid=${sheetGid}`;\n\n // Build batch update request with prefixed ranges\n const batchUpdateData = requests.map((req) => ({\n range: `${sheetTitle}!${req.range}`,\n values: req.values,\n majorDimension: req.majorDimension || 'ROWS',\n }));\n\n logger.info('sheets.values.batchUpdate executing batch request', {\n spreadsheetId: id,\n sheetTitle,\n batchUpdateDataCount: batchUpdateData.length,\n });\n\n // Execute the batch update\n const batchUpdateResponse = await sheets.spreadsheets.values.batchUpdate({\n spreadsheetId: id,\n requestBody: {\n valueInputOption,\n data: batchUpdateData,\n includeValuesInResponse: includeData,\n responseDateTimeRenderOption: 'FORMATTED_STRING',\n responseValueRenderOption: 'FORMATTED_VALUE',\n },\n });\n\n const updateResult = batchUpdateResponse.data;\n\n // Validate batch operation results and detect partial failures\n const responses = updateResult.responses || [];\n const expectedCount = requests.length;\n const actualCount = responses.length;\n\n if (actualCount !== expectedCount) {\n logger.error('Partial batch failure detected', {\n expectedOperations: expectedCount,\n completedOperations: actualCount,\n spreadsheetId: id,\n sheetTitle,\n });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Batch operation partially failed: ${actualCount}/${expectedCount} operations completed`);\n }\n\n // Check for any failed operations (empty or null responses)\n const failedOperations = responses.filter((response, index) => {\n if (!response || !response.updatedRange) {\n logger.error('Failed operation detected', {\n operationIndex: index,\n requestedRange: requests[index]?.range,\n spreadsheetId: id,\n sheetTitle,\n });\n return true;\n }\n return false;\n });\n\n if (failedOperations.length > 0) {\n throw new ProtocolError(ProtocolErrorCode.InternalError, `${failedOperations.length} operations failed to update ranges`);\n }\n\n // Extract updated ranges and calculate totals\n const updatedRanges = responses.map((response) => response.updatedRange || '').filter((range) => range);\n const totalUpdatedRows = updateResult.totalUpdatedRows || 0;\n const totalUpdatedColumns = updateResult.totalUpdatedColumns || 0;\n const totalUpdatedCells = updateResult.totalUpdatedCells || 0;\n\n // Build updated data response if requested\n let updatedData: UpdatedDataItem[] | undefined;\n if (includeData && updateResult.responses) {\n updatedData = updateResult.responses\n .filter((response) => response.updatedData)\n .map((response) => {\n const item: UpdatedDataItem = {\n range: response.updatedRange || '',\n majorDimension: (response.updatedData?.majorDimension as 'ROWS' | 'COLUMNS' | undefined) || 'ROWS',\n };\n const values = response.updatedData?.values as (string | number | boolean | null | undefined)[][] | undefined;\n if (values !== undefined) {\n // Map undefined values to null for JSON Schema compatibility\n item.values = values.map((row) => row.map((cell) => (cell === undefined ? null : cell)));\n }\n return item;\n });\n }\n\n logger.info('sheets.values.batchUpdate completed successfully', {\n totalUpdatedRows,\n totalUpdatedColumns,\n totalUpdatedCells,\n updatedRangesCount: updatedRanges.length,\n });\n\n const result: Output = {\n type: 'success' as const,\n id,\n gid: String(sheetGid),\n spreadsheetTitle: spreadsheetTitle || '',\n spreadsheetUrl: spreadsheetUrl || '',\n sheetTitle,\n sheetUrl,\n totalUpdatedRows,\n totalUpdatedColumns,\n totalUpdatedCells,\n updatedRanges,\n updatedData,\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('Batch update operation failed', {\n id,\n gid,\n requestCount: requests.length,\n valueInputOption,\n error: message,\n });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error batch updating values: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-batch-update',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","ValuesBatchUpdateRequestSchema","z","object","range","A1NotationSchema","describe","values","array","SheetCellSchema","min","majorDimension","enum","inputSchema","id","SpreadsheetIdSchema","gid","SheetGidSchema","requests","valueInputOption","includeData","boolean","successBranchSchema","type","literal","SpreadsheetIdOutput","SheetGidOutput","spreadsheetTitle","string","spreadsheetUrl","sheetTitle","sheetUrl","totalUpdatedRows","number","int","nonnegative","totalUpdatedColumns","totalUpdatedCells","updatedRanges","updatedData","optional","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","spreadsheetData","sheet","sheets","spreadsheetResponse","sheetGid","batchUpdateData","batchUpdateResponse","updateResult","responses","expectedCount","actualCount","failedOperations","error","message","info","requestCount","length","sheetsApi","version","auth","googleAuth","authContext","spreadsheets","get","spreadsheetId","fields","data","properties","title","find","s","String","sheetId","ProtocolError","ProtocolErrorCode","InvalidParams","map","req","batchUpdateDataCount","batchUpdate","requestBody","includeValuesInResponse","responseDateTimeRenderOption","responseValueRenderOption","expectedOperations","completedOperations","InternalError","filter","response","index","updatedRange","operationIndex","requestedRange","item","undefined","row","cell","updatedRangesCount","content","text","JSON","stringify","structuredContent","Error","stack","name"],"mappings":";;;;+BAyOA;;;eAAwBA;;;sBAzOY;2BAEZ;sBAKyB;mBAC/B;4BACS;uBACiG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAN5H,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAeR,gDAAgD;AAChD,IAAME,iCAAiCC,MAAC,CAACC,MAAM,CAAC;IAC9CC,OAAOC,yBAAgB,CAACC,QAAQ,CAAC;IACjCC,QAAQL,MAAC,CAACM,KAAK,CAACN,MAAC,CAACM,KAAK,CAACC,wBAAe,GAAGC,GAAG,CAAC,GAAGJ,QAAQ,CAAC;IAC1DK,gBAAgBT,MAAC,CAACU,IAAI,CAAC;QAAC;Q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;;4BAChEkE,mBAAmB;gCAAElE,QAAAA;4BAAO;wBAC9B;;;oBACOgB;oBACDC,UAAUD,AAAK,YAALA,OAAiBmD,SAAQnD,MAAMC,OAAO,GAAGkB,OAAOnB;oBAChEb,OAAOa,KAAK,CAAC,iCAAiC;wBAC5C/C,IAAAA;wBACAE,KAAAA;wBACAgD,cAAc9C,SAAS+C,MAAM;wBAC7B9C,kBAAAA;wBACA0C,OAAOC;oBACT;oBAEA,MAAM,IAAIoB,qBAAa,CAACC,yBAAiB,CAACY,aAAa,EAAE,AAAC,gCAAuC,OAARjC,UAAW;wBAClGmD,OAAOpD,AAAK,YAALA,OAAiBmD,SAAQnD,MAAMoD,KAAK,GAAGV;oBAChD;;;;;;;IAEJ;;AAEe,SAASzG;IACtB,OAAO;QACLoH,MAAM;QACNvE,QAAAA;QACAG,SAAAA;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/mcp/tools/values-batch-update.ts"],"sourcesContent":["import { sheets as sheetsApi } from '@googleapis/sheets';\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 { z } from 'zod';\nimport { NATIVE_DATE_GUIDANCE } from '../../constants.ts';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { A1NotationSchema, SheetCellSchema, SheetGidOutput, SheetGidSchema, SpreadsheetIdOutput, SpreadsheetIdSchema } from '../../schemas/index.ts';\n\n// Types for updated data response\ninterface UpdatedDataItem {\n range: string;\n majorDimension: 'ROWS' | 'COLUMNS';\n values?: (string | number | boolean | null)[][];\n}\n\n// Input schema for values batch update requests\nconst ValuesBatchUpdateRequestSchema = z.object({\n range: A1NotationSchema.describe('A1 notation range defining the bounded target area. Data dimensions must match range dimensions. Example: D1:D100 requires exactly 100 rows of data. Use open-ended ranges like D1:D to write any number of rows.'),\n values: z.array(z.array(SheetCellSchema)).min(1).describe('2D array of values. Row count must match range height, column count must match range width. Use null to skip a cell (preserve existing value), empty string \"\" to clear it.'),\n majorDimension: z.enum(['ROWS', 'COLUMNS']).describe('Whether values represent rows or columns'),\n});\n\nconst inputSchema = z.object({\n id: SpreadsheetIdSchema,\n gid: SheetGidSchema,\n requests: z.array(ValuesBatchUpdateRequestSchema).min(1).describe('Array of value update requests'),\n valueInputOption: z\n .enum(['RAW', 'USER_ENTERED'])\n .describe('How input data should be interpreted (required; no default is applied by the schema). RAW = exact values: date strings stay text, numeric serials stay numbers. USER_ENTERED = parsed like user input: date strings may become native dates per the workbook locale.'),\n includeData: z.boolean().describe('Whether to include updated cell values in the response'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: SpreadsheetIdOutput,\n gid: SheetGidOutput,\n spreadsheetTitle: z.string().describe('Title of the updated spreadsheet'),\n spreadsheetUrl: z.string().describe('URL of the updated spreadsheet'),\n sheetTitle: z.string().describe('Title of the updated sheet'),\n sheetUrl: z.string().describe('URL of the updated sheet'),\n totalUpdatedRows: z.number().int().nonnegative().describe('Total number of rows updated across all requests'),\n totalUpdatedColumns: z.number().int().nonnegative().describe('Total number of columns updated across all requests'),\n totalUpdatedCells: z.number().int().nonnegative().describe('Total number of cells updated across all requests'),\n updatedRanges: z.array(z.string()).describe('A1 notation ranges that were updated'),\n updatedData: z\n .array(\n z.object({\n range: z.string().describe('A1 notation range that was updated'),\n majorDimension: z.enum(['ROWS', 'COLUMNS']).describe('Dimension of the updated data'),\n values: z.array(z.array(SheetCellSchema)).optional().describe('Updated values (if includeData was true)'),\n })\n )\n .optional()\n .describe('Detailed information about updated data (if includeData was true)'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: `Batch update multiple cell ranges. RAW=exact values, USER_ENTERED=parsed like user input. Use a1-notation prompt for range syntax. For multiple clickable links or rich text inside a single cell, use values-markdown-update. ${NATIVE_DATE_GUIDANCE}`,\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, valueInputOption = 'USER_ENTERED', includeData = false }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('sheets.values.batchUpdate called', {\n id,\n gid,\n requestCount: requests.length,\n valueInputOption,\n includeData,\n });\n\n try {\n const sheets = sheetsApi({ version: 'v4', auth: googleAuth(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 const spreadsheetTitle = spreadsheetData.properties?.title ?? '';\n const spreadsheetUrl = spreadsheetData.spreadsheetUrl ?? '';\n\n // Find sheet by gid\n const sheet = spreadsheetData.sheets?.find((s) => String(s.properties?.sheetId) === gid);\n if (!sheet?.properties) {\n logger.info('Sheet not found for batch 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 const sheetGid = sheet.properties.sheetId ?? 0;\n const sheetUrl = `https://docs.google.com/spreadsheets/d/${id}/edit#gid=${sheetGid}`;\n\n // Build batch update request with prefixed ranges\n const batchUpdateData = requests.map((req) => ({\n range: `${sheetTitle}!${req.range}`,\n values: req.values,\n majorDimension: req.majorDimension || 'ROWS',\n }));\n\n logger.info('sheets.values.batchUpdate executing batch request', {\n spreadsheetId: id,\n sheetTitle,\n batchUpdateDataCount: batchUpdateData.length,\n });\n\n // Execute the batch update\n const batchUpdateResponse = await sheets.spreadsheets.values.batchUpdate({\n spreadsheetId: id,\n requestBody: {\n valueInputOption,\n data: batchUpdateData,\n includeValuesInResponse: includeData,\n responseDateTimeRenderOption: 'FORMATTED_STRING',\n responseValueRenderOption: 'FORMATTED_VALUE',\n },\n });\n\n const updateResult = batchUpdateResponse.data;\n\n // Validate batch operation results and detect partial failures\n const responses = updateResult.responses || [];\n const expectedCount = requests.length;\n const actualCount = responses.length;\n\n if (actualCount !== expectedCount) {\n logger.error('Partial batch failure detected', {\n expectedOperations: expectedCount,\n completedOperations: actualCount,\n spreadsheetId: id,\n sheetTitle,\n });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Batch operation partially failed: ${actualCount}/${expectedCount} operations completed`);\n }\n\n // Check for any failed operations (empty or null responses)\n const failedOperations = responses.filter((response, index) => {\n if (!response || !response.updatedRange) {\n logger.error('Failed operation detected', {\n operationIndex: index,\n requestedRange: requests[index]?.range,\n spreadsheetId: id,\n sheetTitle,\n });\n return true;\n }\n return false;\n });\n\n if (failedOperations.length > 0) {\n throw new ProtocolError(ProtocolErrorCode.InternalError, `${failedOperations.length} operations failed to update ranges`);\n }\n\n // Extract updated ranges and calculate totals\n const updatedRanges = responses.map((response) => response.updatedRange || '').filter((range) => range);\n const totalUpdatedRows = updateResult.totalUpdatedRows || 0;\n const totalUpdatedColumns = updateResult.totalUpdatedColumns || 0;\n const totalUpdatedCells = updateResult.totalUpdatedCells || 0;\n\n // Build updated data response if requested\n let updatedData: UpdatedDataItem[] | undefined;\n if (includeData && updateResult.responses) {\n updatedData = updateResult.responses\n .filter((response) => response.updatedData)\n .map((response) => {\n const item: UpdatedDataItem = {\n range: response.updatedRange || '',\n majorDimension: (response.updatedData?.majorDimension as 'ROWS' | 'COLUMNS' | undefined) || 'ROWS',\n };\n const values = response.updatedData?.values as (string | number | boolean | null | undefined)[][] | undefined;\n if (values !== undefined) {\n // Map undefined values to null for JSON Schema compatibility\n item.values = values.map((row) => row.map((cell) => (cell === undefined ? null : cell)));\n }\n return item;\n });\n }\n\n logger.info('sheets.values.batchUpdate completed successfully', {\n totalUpdatedRows,\n totalUpdatedColumns,\n totalUpdatedCells,\n updatedRangesCount: updatedRanges.length,\n });\n\n const result: Output = {\n type: 'success' as const,\n id,\n gid: String(sheetGid),\n spreadsheetTitle: spreadsheetTitle || '',\n spreadsheetUrl: spreadsheetUrl || '',\n sheetTitle,\n sheetUrl,\n totalUpdatedRows,\n totalUpdatedColumns,\n totalUpdatedCells,\n updatedRanges,\n updatedData,\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('Batch update operation failed', {\n id,\n gid,\n requestCount: requests.length,\n valueInputOption,\n error: message,\n });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error batch updating values: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'values-batch-update',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","ValuesBatchUpdateRequestSchema","z","object","range","A1NotationSchema","describe","values","array","SheetCellSchema","min","majorDimension","enum","inputSchema","id","SpreadsheetIdSchema","gid","SheetGidSchema","requests","valueInputOption","includeData","boolean","successBranchSchema","type","literal","SpreadsheetIdOutput","SheetGidOutput","spreadsheetTitle","string","spreadsheetUrl","sheetTitle","sheetUrl","totalUpdatedRows","number","int","nonnegative","totalUpdatedColumns","totalUpdatedCells","updatedRanges","updatedData","optional","outputSchema","discriminatedUnion","config","description","NATIVE_DATE_GUIDANCE","result","handler","extra","logger","spreadsheetData","sheet","sheets","spreadsheetResponse","sheetGid","batchUpdateData","batchUpdateResponse","updateResult","responses","expectedCount","actualCount","failedOperations","error","message","info","requestCount","length","sheetsApi","version","auth","googleAuth","authContext","spreadsheets","get","spreadsheetId","fields","data","properties","title","find","s","String","sheetId","ProtocolError","ProtocolErrorCode","InvalidParams","map","req","batchUpdateDataCount","batchUpdate","requestBody","includeValuesInResponse","responseDateTimeRenderOption","responseValueRenderOption","expectedOperations","completedOperations","InternalError","filter","response","index","updatedRange","operationIndex","requestedRange","item","undefined","row","cell","updatedRangesCount","content","text","JSON","stringify","structuredContent","Error","stack","name"],"mappings":";;;;+BA4OA;;;eAAwBA;;;sBA5OY;2BAEZ;sBAKyB;mBAC/B;2BACmB;4BACV;uBACiG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAP5H,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAgBR,gDAAgD;AAChD,IAAME,iCAAiCC,MAAC,CAACC,MAAM,CAAC;IAC9CC,OAAOC,yBAAgB,CAACC,QAAQ,CAAC;IACjCC,QAAQL,MAAC,CAACM,KAAK,CAACN,MAAC,CAACM,KAAK,CAACC,wBAAe,GAAGC,GAAG,CAAC,GAAGJ,QAAQ,CAAC;IAC1DK,gBAAgBT,MAAC,CAACU,IAAI,CAAC;QAAC;QAAQ;KAAU,EAAEN,QAAQ,CAAC;AACvD;AAEA,IAAMO,cAAcX,MAAC,CAACC,MAAM,CAAC;IAC3BW,IAAIC,4BAAmB;IACvBC,KAAKC,uBAAc;IACnBC,UAAUhB,MAAC,CAACM,KAAK,CAACP,gCAAgCS,GAAG,CAAC,GAAGJ,QAAQ,CAAC;IAClEa,kBAAkBjB,MAAC,CAChBU,IAAI,CAAC;QAAC;QAAO;KAAe,EAC5BN,QAAQ,CAAC;IACZc,aAAalB,MAAC,CAACmB,OAAO,GAAGf,QAAQ,CAAC;AACpC;AAEA,IAAMgB,sBAAsBpB,MAAC,CAACC,MAAM,CAAC;IACnCoB,MAAMrB,MAAC,CAACsB,OAAO,CAAC;IAChBV,IAAIW,4BAAmB;IACvBT,KAAKU,uBAAc;IACnBC,kBAAkBzB,MAAC,CAAC0B,MAAM,GAAGtB,QA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AAA;IACF;AACF"}
|
|
@@ -37,7 +37,7 @@ declare function handler({ id, gid, sourceUri, startRange, valueInputOption, sou
|
|
|
37
37
|
export default function createTool(): {
|
|
38
38
|
name: string;
|
|
39
39
|
config: {
|
|
40
|
-
readonly description: "Import CSV to sheet range. Overwrites existing data at startRange. Use rows-csv-append for database-style appends with deduplication.";
|
|
40
|
+
readonly description: "Import CSV to sheet range. Overwrites existing data at startRange. Use rows-csv-append for database-style appends with deduplication. Dates: a date-looking string is not necessarily a native date. See values-batch-update for the native-date write, format and read-back steps.";
|
|
41
41
|
readonly inputSchema: z.ZodObject<{
|
|
42
42
|
id: z.ZodString;
|
|
43
43
|
gid: z.ZodCoercedString<unknown>;
|
|
@@ -37,7 +37,7 @@ declare function handler({ id, gid, sourceUri, startRange, valueInputOption, sou
|
|
|
37
37
|
export default function createTool(): {
|
|
38
38
|
name: string;
|
|
39
39
|
config: {
|
|
40
|
-
readonly description: "Import CSV to sheet range. Overwrites existing data at startRange. Use rows-csv-append for database-style appends with deduplication.";
|
|
40
|
+
readonly description: "Import CSV to sheet range. Overwrites existing data at startRange. Use rows-csv-append for database-style appends with deduplication. Dates: a date-looking string is not necessarily a native date. See values-batch-update for the native-date write, format and read-back steps.";
|
|
41
41
|
readonly inputSchema: z.ZodObject<{
|
|
42
42
|
id: z.ZodString;
|
|
43
43
|
gid: z.ZodCoercedString<unknown>;
|
|
@@ -13,6 +13,7 @@ var _oauthgoogle = require("@mcp-z/oauth-google");
|
|
|
13
13
|
var _server = require("@mcp-z/server");
|
|
14
14
|
var _csvparse = require("csv-parse");
|
|
15
15
|
var _zod = require("zod");
|
|
16
|
+
var _constantsts = require("../../constants.js");
|
|
16
17
|
var _googleauthts = require("../../lib/google-auth.js");
|
|
17
18
|
var _indexts = require("../../schemas/index.js");
|
|
18
19
|
var _csvstreamingts = require("../../spreadsheet/csv-streaming.js");
|
|
@@ -198,7 +199,7 @@ var inputSchema = _zod.z.object({
|
|
|
198
199
|
valueInputOption: _zod.z.enum([
|
|
199
200
|
'RAW',
|
|
200
201
|
'USER_ENTERED'
|
|
201
|
-
]).default('USER_ENTERED').describe('How to interpret values (RAW = exact,
|
|
202
|
+
]).default('USER_ENTERED').describe('How to interpret values (default USER_ENTERED = parse formulas/dates per the workbook locale; RAW = exact, date-looking CSV text stays text)'),
|
|
202
203
|
sourceHasHeaders: _zod.z.boolean().default(true).describe('First row is headers (metadata) - exclude from data range. Set to false to include first row as data.')
|
|
203
204
|
});
|
|
204
205
|
var successBranchSchema = _zod.z.object({
|
|
@@ -219,7 +220,7 @@ var outputSchema = _zod.z.discriminatedUnion('type', [
|
|
|
219
220
|
AuthRequiredBranchSchema
|
|
220
221
|
]);
|
|
221
222
|
var config = {
|
|
222
|
-
description:
|
|
223
|
+
description: "Import CSV to sheet range. Overwrites existing data at startRange. Use rows-csv-append for database-style appends with deduplication. ".concat(_constantsts.NATIVE_DATE_POINTER),
|
|
223
224
|
inputSchema: inputSchema,
|
|
224
225
|
outputSchema: _zod.z.object({
|
|
225
226
|
result: outputSchema
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/open-source/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 { sheets as sheetsApi } from '@googleapis/sheets';\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 { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\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 = sheetsApi({ version: 'v4', auth: googleAuth(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","sheetsApi","version","auth","googleAuth","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;;;;+BAiMhF;;;eAAwBA;;;sBA/LY;2BAEZ;sBAKyB;wBAC3B;mBACJ;4BACS;uBACgF;8BAC1E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AARjC,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAUR,gGAAgG,GAChG,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F;AACF"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/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 { sheets as sheetsApi } from '@googleapis/sheets';\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 { z } from 'zod';\nimport { NATIVE_DATE_POINTER } from '../../constants.ts';\nimport { googleAuth } from '../../lib/google-auth.ts';\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 (default USER_ENTERED = parse formulas/dates per the workbook locale; RAW = exact, date-looking CSV text stays text)'),\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. ${NATIVE_DATE_POINTER}`,\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 = sheetsApi({ version: 'v4', auth: googleAuth(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","NATIVE_DATE_POINTER","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","sheetsApi","version","auth","googleAuth","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;;;;+BAkMhF;;;eAAwBA;;;sBAhMY;2BAEZ;sBAKyB;wBAC3B;mBACJ;2BACkB;4BACT;uBACgF;8BAC1E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AATjC,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAWR,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;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C,UAAU,AAAC,0CAAwDe,OAAfvC,IAAG,cAAqC,OAAzBuC,MAAMqC,UAAU,CAACC,OAAO;wBAC3FpD,cAAckC;wBACdjC,aAAa+B;wBACb7B,gBAAgB8B;wBAChB7B,cAAc2B;oBAChB;oBAEA;;wBAAO;4BACLoD,OAAO;gCAAG;oCAAE3F,MAAM;oCAAiB4F,MAAMC,KAAKC,SAAS,CAAC5E;gCAAQ;;4BAChE6E,mBAAmB;gCAAE7E,QAAAA;4BAAO;wBAC9B;;;oBACOyB;oBACDC,UAAUD,AAAK,YAALA,OAAiBqD,SAAQrD,MAAMC,OAAO,GAAGc,OAAOf;oBAChEtB,OAAOsB,KAAK,CAAC,kCAAkC;wBAAEA,OAAOC;oBAAQ;oBAEhE,MAAM,IAAIiB,qBAAa,CAACC,yBAAiB,CAACmC,aAAa,EAAE,AAAC,mCAA0C,OAARrD,UAAW;wBACrGsD,OAAOvD,AAAK,YAALA,OAAiBqD,SAAQrD,MAAMuD,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAAS3H;IACtB,OAAO;QACL4H,MAAM;QACNrF,QAAAA;QACAI,SAAAA;IACF;AACF"}
|
|
@@ -13,8 +13,8 @@ declare const inputSchema: z.ZodObject<{
|
|
|
13
13
|
values: z.ZodOptional<z.ZodBoolean>;
|
|
14
14
|
a1s: z.ZodOptional<z.ZodBoolean>;
|
|
15
15
|
render: z.ZodOptional<z.ZodEnum<{
|
|
16
|
-
FORMATTED_VALUE: "FORMATTED_VALUE";
|
|
17
16
|
UNFORMATTED_VALUE: "UNFORMATTED_VALUE";
|
|
17
|
+
FORMATTED_VALUE: "FORMATTED_VALUE";
|
|
18
18
|
FORMULA: "FORMULA";
|
|
19
19
|
}>>;
|
|
20
20
|
matchCase: z.ZodOptional<z.ZodBoolean>;
|
|
@@ -49,8 +49,8 @@ export default function createTool(): {
|
|
|
49
49
|
values: z.ZodOptional<z.ZodBoolean>;
|
|
50
50
|
a1s: z.ZodOptional<z.ZodBoolean>;
|
|
51
51
|
render: z.ZodOptional<z.ZodEnum<{
|
|
52
|
-
FORMATTED_VALUE: "FORMATTED_VALUE";
|
|
53
52
|
UNFORMATTED_VALUE: "UNFORMATTED_VALUE";
|
|
53
|
+
FORMATTED_VALUE: "FORMATTED_VALUE";
|
|
54
54
|
FORMULA: "FORMULA";
|
|
55
55
|
}>>;
|
|
56
56
|
matchCase: z.ZodOptional<z.ZodBoolean>;
|
|
@@ -13,8 +13,8 @@ declare const inputSchema: z.ZodObject<{
|
|
|
13
13
|
values: z.ZodOptional<z.ZodBoolean>;
|
|
14
14
|
a1s: z.ZodOptional<z.ZodBoolean>;
|
|
15
15
|
render: z.ZodOptional<z.ZodEnum<{
|
|
16
|
-
FORMATTED_VALUE: "FORMATTED_VALUE";
|
|
17
16
|
UNFORMATTED_VALUE: "UNFORMATTED_VALUE";
|
|
17
|
+
FORMATTED_VALUE: "FORMATTED_VALUE";
|
|
18
18
|
FORMULA: "FORMULA";
|
|
19
19
|
}>>;
|
|
20
20
|
matchCase: z.ZodOptional<z.ZodBoolean>;
|
|
@@ -49,8 +49,8 @@ export default function createTool(): {
|
|
|
49
49
|
values: z.ZodOptional<z.ZodBoolean>;
|
|
50
50
|
a1s: z.ZodOptional<z.ZodBoolean>;
|
|
51
51
|
render: z.ZodOptional<z.ZodEnum<{
|
|
52
|
-
FORMATTED_VALUE: "FORMATTED_VALUE";
|
|
53
52
|
UNFORMATTED_VALUE: "UNFORMATTED_VALUE";
|
|
53
|
+
FORMATTED_VALUE: "FORMATTED_VALUE";
|
|
54
54
|
FORMULA: "FORMULA";
|
|
55
55
|
}>>;
|
|
56
56
|
matchCase: z.ZodOptional<z.ZodBoolean>;
|
|
@@ -12,6 +12,7 @@ var _sheets = require("@googleapis/sheets");
|
|
|
12
12
|
var _oauthgoogle = require("@mcp-z/oauth-google");
|
|
13
13
|
var _server = require("@mcp-z/server");
|
|
14
14
|
var _zod = require("zod");
|
|
15
|
+
var _constantsts = require("../../constants.js");
|
|
15
16
|
var _googleauthts = require("../../lib/google-auth.js");
|
|
16
17
|
var _indexts = require("../../schemas/index.js");
|
|
17
18
|
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
|
|
@@ -198,7 +199,7 @@ var inputSchema = _zod.z.object({
|
|
|
198
199
|
'FORMATTED_VALUE',
|
|
199
200
|
'UNFORMATTED_VALUE',
|
|
200
201
|
'FORMULA'
|
|
201
|
-
]).optional().describe(
|
|
202
|
+
]).optional().describe(_constantsts.RENDER_DESCRIPTION),
|
|
202
203
|
matchCase: _zod.z.boolean().optional().describe('Case-sensitive matching. Default is false (case-insensitive).')
|
|
203
204
|
});
|
|
204
205
|
var successBranchSchema = _zod.z.object({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/mcp/tools/values-search.ts"],"sourcesContent":["import { sheets as sheetsApi } from '@googleapis/sheets';\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 { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\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 = sheetsApi({ version: 'v4', auth: googleAuth(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","sheetsApi","version","auth","googleAuth","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":";;;;+BA8MA;;;eAAwBA;;;sBA9MY;2BAEZ;sBAKyB;mBAC/B;4BACS;uBAC0C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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/CC,MAAMI,KAAKC,KAAK,CAAC,AAACL,CAAAA,MAAM,CAAA,IAAK;IAC/B;IACA,OAAOD;AACT;AAEA,IAAMO,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,IAAIC,4BAAmB;IACvBC,KAAKC,uBAAc;IACnBC,OAAON,MAAC,CAACO,MAAM,CAACC,MAAM,GAAGC,IAAI,GAAGC,QAAQ,GAAGC,QAAQ,CAAC;IACpDC,QAAQZ,MAAC,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AGhE;;wBAAO;4BACLqD,OAAO;gCAAG;oCAAEnF,MAAM;oCAAiBoF,MAAMC,KAAKC,SAAS,CAACzE;gCAAQ;;4BAChE0E,mBAAmB;gCAAE1E,QAAAA;4BAAO;wBAC9B;;;oBACO+B;oBACDC,UAAUD,AAAK,YAALA,OAAiB4C,SAAQ5C,MAAMC,OAAO,GAAGtE,OAAOqE;oBAChE5B,OAAO4B,KAAK,CAAC,8BAA8B;wBAAEA,OAAOC;oBAAQ;oBAE5D,MAAM,IAAIgB,qBAAa,CAACC,yBAAiB,CAAC2B,aAAa,EAAE,AAAC,gCAAuC,OAAR5C,UAAW;wBAClG6C,OAAO9C,AAAK,YAALA,OAAiB4C,SAAQ5C,MAAM8C,KAAK,GAAGV;oBAChD;;;;;;;IAEJ;;AAEe,SAASjH;IACtB,OAAO;QACL4H,MAAM;QACNhF,QAAAA;QACAG,SAAAA;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/mcp/tools/values-search.ts"],"sourcesContent":["import { sheets as sheetsApi } from '@googleapis/sheets';\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 { z } from 'zod';\nimport { RENDER_DESCRIPTION } from '../../constants.ts';\nimport { googleAuth } from '../../lib/google-auth.ts';\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(RENDER_DESCRIPTION),\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 = sheetsApi({ version: 'v4', auth: googleAuth(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","RENDER_DESCRIPTION","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","sheetsApi","version","auth","googleAuth","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":";;;;+BA+MA;;;eAAwBA;;;sBA/MY;2BAEZ;sBAKyB;mBAC/B;2BACiB;4BACR;uBAC0C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,KAAKC,KAAK,CAAC,AAACL,CAAAA,MAAM,CAAA,IAAK;IAC/B;IACA,OAAOD;AACT;AAEA,IAAMO,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,IAAIC,4BAAmB;IACvBC,KAAKC,uBAAc;IACnBC,OAAON,M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KAAK;wBAAE/E,KAAKkC;oBAAQ,GAC5CpC,UAAUqC,YAAY4C,MAAM,GAAG,KAAK;wBAAEjF,QAAQqC;oBAAY;oBAGhE;;wBAAO;4BACLqD,OAAO;gCAAG;oCAAEnF,MAAM;oCAAiBoF,MAAMC,KAAKC,SAAS,CAACzE;gCAAQ;;4BAChE0E,mBAAmB;gCAAE1E,QAAAA;4BAAO;wBAC9B;;;oBACO+B;oBACDC,UAAUD,AAAK,YAALA,OAAiB4C,SAAQ5C,MAAMC,OAAO,GAAGvE,OAAOsE;oBAChE5B,OAAO4B,KAAK,CAAC,8BAA8B;wBAAEA,OAAOC;oBAAQ;oBAE5D,MAAM,IAAIgB,qBAAa,CAACC,yBAAiB,CAAC2B,aAAa,EAAE,AAAC,gCAAuC,OAAR5C,UAAW;wBAClG6C,OAAO9C,AAAK,YAALA,OAAiB4C,SAAQ5C,MAAM8C,KAAK,GAAGV;oBAChD;;;;;;;IAEJ;;AAEe,SAASlH;IACtB,OAAO;QACL6H,MAAM;QACNhF,QAAAA;QACAG,SAAAA;IACF;AACF"}
|
package/dist/cjs/setup/http.js
CHANGED
|
@@ -166,7 +166,7 @@ function _unsupported_iterable_to_array(o, minLen) {
|
|
|
166
166
|
if (typeof o === "string") return _array_like_to_array(o, minLen);
|
|
167
167
|
var n = Object.prototype.toString.call(o).slice(8, -1);
|
|
168
168
|
if (n === "Object" && o.constructor) n = o.constructor.name;
|
|
169
|
-
if (n === "Map" || n === "Set") return Array.from(
|
|
169
|
+
if (n === "Map" || n === "Set") return Array.from(o);
|
|
170
170
|
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
|
|
171
171
|
}
|
|
172
172
|
function createHTTPServer(config, overrides) {
|
|
@@ -3,8 +3,8 @@ import type { Logger, MiddlewareLayer } from '@mcp-z/server';
|
|
|
3
3
|
import type { CommonRuntime, RuntimeOverrides, ServerConfig } from '../types.js';
|
|
4
4
|
import { type OAuthAdapters } from './oauth-google.js';
|
|
5
5
|
export declare function createLogger(config: ServerConfig): Logger;
|
|
6
|
-
export declare function createTokenStore(baseDir: string): Promise<import("keyv").Keyv<CachedToken>>;
|
|
7
|
-
export declare function createDcrStore(baseDir: string, required: boolean): Promise<import("keyv").Keyv<unknown> | undefined>;
|
|
6
|
+
export declare function createTokenStore(baseDir: string, logger?: Logger): Promise<import("keyv").Keyv<CachedToken>>;
|
|
7
|
+
export declare function createDcrStore(baseDir: string, required: boolean, logger?: Logger): Promise<import("keyv").Keyv<unknown> | undefined>;
|
|
8
8
|
export declare function createAuthLayer(authMiddleware: OAuthAdapters['middleware']): MiddlewareLayer;
|
|
9
9
|
export declare function createLoggingLayer(logger: Logger): MiddlewareLayer;
|
|
10
10
|
export declare function createDefaultRuntime(config: ServerConfig, overrides?: RuntimeOverrides): Promise<CommonRuntime>;
|
|
@@ -3,8 +3,8 @@ import type { Logger, MiddlewareLayer } from '@mcp-z/server';
|
|
|
3
3
|
import type { CommonRuntime, RuntimeOverrides, ServerConfig } from '../types.js';
|
|
4
4
|
import { type OAuthAdapters } from './oauth-google.js';
|
|
5
5
|
export declare function createLogger(config: ServerConfig): Logger;
|
|
6
|
-
export declare function createTokenStore(baseDir: string): Promise<import("keyv").Keyv<CachedToken>>;
|
|
7
|
-
export declare function createDcrStore(baseDir: string, required: boolean): Promise<import("keyv").Keyv<unknown> | undefined>;
|
|
6
|
+
export declare function createTokenStore(baseDir: string, logger?: Logger): Promise<import("keyv").Keyv<CachedToken>>;
|
|
7
|
+
export declare function createDcrStore(baseDir: string, required: boolean, logger?: Logger): Promise<import("keyv").Keyv<unknown> | undefined>;
|
|
8
8
|
export declare function createAuthLayer(authMiddleware: OAuthAdapters['middleware']): MiddlewareLayer;
|
|
9
9
|
export declare function createLoggingLayer(logger: Logger): MiddlewareLayer;
|
|
10
10
|
export declare function createDefaultRuntime(config: ServerConfig, overrides?: RuntimeOverrides): Promise<CommonRuntime>;
|
|
@@ -212,19 +212,19 @@ function createLogger(config) {
|
|
|
212
212
|
sync: false
|
|
213
213
|
}) : _pino.default.destination(1));
|
|
214
214
|
}
|
|
215
|
-
function createTokenStore(baseDir) {
|
|
215
|
+
function createTokenStore(baseDir, logger) {
|
|
216
216
|
return _async_to_generator(function() {
|
|
217
217
|
var tokenStoreUri;
|
|
218
218
|
return _ts_generator(this, function(_state) {
|
|
219
219
|
tokenStoreUri = process.env.TOKEN_STORE_URI || (0, _nodeurl.pathToFileURL)(_path.join(baseDir, 'tokens.json')).href;
|
|
220
220
|
return [
|
|
221
221
|
2,
|
|
222
|
-
(0, _createstorets.default)(tokenStoreUri)
|
|
222
|
+
(0, _createstorets.default)(tokenStoreUri, logger)
|
|
223
223
|
];
|
|
224
224
|
});
|
|
225
225
|
})();
|
|
226
226
|
}
|
|
227
|
-
function createDcrStore(baseDir, required) {
|
|
227
|
+
function createDcrStore(baseDir, required, logger) {
|
|
228
228
|
return _async_to_generator(function() {
|
|
229
229
|
var dcrStoreUri;
|
|
230
230
|
return _ts_generator(this, function(_state) {
|
|
@@ -235,7 +235,7 @@ function createDcrStore(baseDir, required) {
|
|
|
235
235
|
dcrStoreUri = process.env.DCR_STORE_URI || (0, _nodeurl.pathToFileURL)(_path.join(baseDir, 'dcr.json')).href;
|
|
236
236
|
return [
|
|
237
237
|
2,
|
|
238
|
-
(0, _createstorets.default)(dcrStoreUri)
|
|
238
|
+
(0, _createstorets.default)(dcrStoreUri, logger)
|
|
239
239
|
];
|
|
240
240
|
});
|
|
241
241
|
})();
|
|
@@ -267,14 +267,14 @@ function createDefaultRuntime(config, overrides) {
|
|
|
267
267
|
logger = createLogger(config);
|
|
268
268
|
return [
|
|
269
269
|
4,
|
|
270
|
-
createTokenStore(config.baseDir)
|
|
270
|
+
createTokenStore(config.baseDir, logger)
|
|
271
271
|
];
|
|
272
272
|
case 1:
|
|
273
273
|
tokenStore = _state.sent();
|
|
274
274
|
baseUrl = (_config_baseUrl = config.baseUrl) !== null && _config_baseUrl !== void 0 ? _config_baseUrl : config.transport.type === 'http' && config.transport.port ? "http://localhost:".concat(config.transport.port) : undefined;
|
|
275
275
|
return [
|
|
276
276
|
4,
|
|
277
|
-
createDcrStore(config.baseDir, config.auth === 'dcr')
|
|
277
|
+
createDcrStore(config.baseDir, config.auth === 'dcr', logger)
|
|
278
278
|
];
|
|
279
279
|
case 2:
|
|
280
280
|
dcrStore = _state.sent();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/setup/runtime.ts"],"sourcesContent":["import { pathToFileURL } from 'node:url';\nimport { sanitizeForLoggingFormatter } from '@mcp-z/oauth';\nimport type { CachedToken } from '@mcp-z/oauth-google';\nimport type { Logger, MiddlewareLayer } from '@mcp-z/server';\nimport { createLoggingMiddleware } from '@mcp-z/server';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport pino from 'pino';\nimport createStore from '../lib/create-store.ts';\nimport * as mcp from '../mcp/index.ts';\nimport type { CommonRuntime, RuntimeDeps, RuntimeOverrides, ServerConfig } from '../types.ts';\nimport { createOAuthAdapters, type OAuthAdapters } from './oauth-google.ts';\n\nexport function createLogger(config: ServerConfig): Logger {\n const hasStdio = config.transport.type === 'stdio';\n const logsPath = path.join(config.baseDir, 'logs', `${config.name}.log`);\n if (hasStdio) fs.mkdirSync(path.dirname(logsPath), { recursive: true });\n return pino({ level: config.logLevel ?? 'info', formatters: sanitizeForLoggingFormatter() }, hasStdio ? pino.destination({ dest: logsPath, sync: false }) : pino.destination(1));\n}\n\nexport async function createTokenStore(baseDir: string) {\n const tokenStoreUri = process.env.TOKEN_STORE_URI || pathToFileURL(path.join(baseDir, 'tokens.json')).href;\n return createStore<CachedToken>(tokenStoreUri);\n}\n\nexport async function createDcrStore(baseDir: string, required: boolean) {\n if (!required) return undefined;\n const dcrStoreUri = process.env.DCR_STORE_URI || pathToFileURL(path.join(baseDir, 'dcr.json')).href;\n return createStore<unknown>(dcrStoreUri);\n}\n\nexport function createAuthLayer(authMiddleware: OAuthAdapters['middleware']): MiddlewareLayer {\n return {\n withTool: authMiddleware.withToolAuth,\n withResource: authMiddleware.withResourceAuth,\n withPrompt: authMiddleware.withPromptAuth,\n };\n}\n\nexport function createLoggingLayer(logger: Logger): MiddlewareLayer {\n const logging = createLoggingMiddleware({ logger });\n return {\n withTool: logging.withToolLogging,\n withResource: logging.withResourceLogging,\n withPrompt: logging.withPromptLogging,\n };\n}\n\nexport async function createDefaultRuntime(config: ServerConfig, overrides?: RuntimeOverrides): Promise<CommonRuntime> {\n if (config.auth === 'dcr' && config.transport.type !== 'http') throw new Error('DCR mode requires an HTTP transport');\n\n const logger = createLogger(config);\n const tokenStore = await createTokenStore(config.baseDir);\n const baseUrl = config.baseUrl ?? (config.transport.type === 'http' && config.transport.port ? `http://localhost:${config.transport.port}` : undefined);\n const dcrStore = await createDcrStore(config.baseDir, config.auth === 'dcr');\n const oauthAdapters = await createOAuthAdapters(config, { logger, tokenStore, dcrStore }, baseUrl);\n const deps: RuntimeDeps = { config, logger, tokenStore, oauthAdapters, baseUrl };\n const createDomainModules =\n overrides?.createDomainModules ??\n (() => ({\n tools: Object.values(mcp.toolFactories).map((factory) => factory()),\n resources: Object.values(mcp.resourceFactories).map((factory) => factory()),\n prompts: Object.values(mcp.promptFactories).map((factory) => factory()),\n }));\n const middlewareFactories = overrides?.middlewareFactories ?? [() => createAuthLayer(oauthAdapters.middleware), () => createLoggingLayer(logger)];\n\n return {\n deps,\n middlewareFactories,\n createDomainModules,\n close: async () => {},\n };\n}\n"],"names":["createAuthLayer","createDcrStore","createDefaultRuntime","createLogger","createLoggingLayer","createTokenStore","config","hasStdio","transport","type","logsPath","path","join","baseDir","name","fs","mkdirSync","dirname","recursive","pino","level","logLevel","formatters","sanitizeForLoggingFormatter","destination","dest","sync","tokenStoreUri","process","env","TOKEN_STORE_URI","pathToFileURL","href","createStore","required","dcrStoreUri","undefined","DCR_STORE_URI","authMiddleware","withTool","withToolAuth","withResource","withResourceAuth","withPrompt","withPromptAuth","
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-sheets/src/setup/runtime.ts"],"sourcesContent":["import { pathToFileURL } from 'node:url';\nimport { sanitizeForLoggingFormatter } from '@mcp-z/oauth';\nimport type { CachedToken } from '@mcp-z/oauth-google';\nimport type { Logger, MiddlewareLayer } from '@mcp-z/server';\nimport { createLoggingMiddleware } from '@mcp-z/server';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport pino from 'pino';\nimport createStore from '../lib/create-store.ts';\nimport * as mcp from '../mcp/index.ts';\nimport type { CommonRuntime, RuntimeDeps, RuntimeOverrides, ServerConfig } from '../types.ts';\nimport { createOAuthAdapters, type OAuthAdapters } from './oauth-google.ts';\n\nexport function createLogger(config: ServerConfig): Logger {\n const hasStdio = config.transport.type === 'stdio';\n const logsPath = path.join(config.baseDir, 'logs', `${config.name}.log`);\n if (hasStdio) fs.mkdirSync(path.dirname(logsPath), { recursive: true });\n return pino({ level: config.logLevel ?? 'info', formatters: sanitizeForLoggingFormatter() }, hasStdio ? pino.destination({ dest: logsPath, sync: false }) : pino.destination(1));\n}\n\nexport async function createTokenStore(baseDir: string, logger?: Logger) {\n const tokenStoreUri = process.env.TOKEN_STORE_URI || pathToFileURL(path.join(baseDir, 'tokens.json')).href;\n return createStore<CachedToken>(tokenStoreUri, logger);\n}\n\nexport async function createDcrStore(baseDir: string, required: boolean, logger?: Logger) {\n if (!required) return undefined;\n const dcrStoreUri = process.env.DCR_STORE_URI || pathToFileURL(path.join(baseDir, 'dcr.json')).href;\n return createStore<unknown>(dcrStoreUri, logger);\n}\n\nexport function createAuthLayer(authMiddleware: OAuthAdapters['middleware']): MiddlewareLayer {\n return {\n withTool: authMiddleware.withToolAuth,\n withResource: authMiddleware.withResourceAuth,\n withPrompt: authMiddleware.withPromptAuth,\n };\n}\n\nexport function createLoggingLayer(logger: Logger): MiddlewareLayer {\n const logging = createLoggingMiddleware({ logger });\n return {\n withTool: logging.withToolLogging,\n withResource: logging.withResourceLogging,\n withPrompt: logging.withPromptLogging,\n };\n}\n\nexport async function createDefaultRuntime(config: ServerConfig, overrides?: RuntimeOverrides): Promise<CommonRuntime> {\n if (config.auth === 'dcr' && config.transport.type !== 'http') throw new Error('DCR mode requires an HTTP transport');\n\n const logger = createLogger(config);\n const tokenStore = await createTokenStore(config.baseDir, logger);\n const baseUrl = config.baseUrl ?? (config.transport.type === 'http' && config.transport.port ? `http://localhost:${config.transport.port}` : undefined);\n const dcrStore = await createDcrStore(config.baseDir, config.auth === 'dcr', logger);\n const oauthAdapters = await createOAuthAdapters(config, { logger, tokenStore, dcrStore }, baseUrl);\n const deps: RuntimeDeps = { config, logger, tokenStore, oauthAdapters, baseUrl };\n const createDomainModules =\n overrides?.createDomainModules ??\n (() => ({\n tools: Object.values(mcp.toolFactories).map((factory) => factory()),\n resources: Object.values(mcp.resourceFactories).map((factory) => factory()),\n prompts: Object.values(mcp.promptFactories).map((factory) => factory()),\n }));\n const middlewareFactories = overrides?.middlewareFactories ?? [() => createAuthLayer(oauthAdapters.middleware), () => createLoggingLayer(logger)];\n\n return {\n deps,\n middlewareFactories,\n createDomainModules,\n close: async () => {},\n };\n}\n"],"names":["createAuthLayer","createDcrStore","createDefaultRuntime","createLogger","createLoggingLayer","createTokenStore","config","hasStdio","transport","type","logsPath","path","join","baseDir","name","fs","mkdirSync","dirname","recursive","pino","level","logLevel","formatters","sanitizeForLoggingFormatter","destination","dest","sync","logger","tokenStoreUri","process","env","TOKEN_STORE_URI","pathToFileURL","href","createStore","required","dcrStoreUri","undefined","DCR_STORE_URI","authMiddleware","withTool","withToolAuth","withResource","withResourceAuth","withPrompt","withPromptAuth","logging","createLoggingMiddleware","withToolLogging","withResourceLogging","withPromptLogging","overrides","tokenStore","baseUrl","dcrStore","oauthAdapters","deps","createDomainModules","middlewareFactories","auth","Error","port","createOAuthAdapters","tools","Object","values","mcp","toolFactories","map","factory","resources","resour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AS,GAAGD;;;oBAApFE,gBAAgB;oBAChBC,OAAoB;wBAAElD,QAAAA;wBAAQqB,QAAAA;wBAAQyB,YAAAA;wBAAYG,eAAAA;wBAAeF,SAAAA;oBAAQ;oBACzEI,8BACJN,sBAAAA,gCAAAA,UAAWM,mBAAmB,uCAC7B;+BAAO;4BACNM,OAAOC,OAAOC,MAAM,CAACC,SAAIC,aAAa,EAAEC,GAAG,CAAC,SAACC;uCAAYA;;4BACzDC,WAAWN,OAAOC,MAAM,CAACC,SAAIK,iBAAiB,EAAEH,GAAG,CAAC,SAACC;uCAAYA;;4BACjEG,SAASR,OAAOC,MAAM,CAACC,SAAIO,eAAe,EAAEL,GAAG,CAAC,SAACC;uCAAYA;;wBAC/D;;oBACIX,+BAAsBP,sBAAAA,gCAAAA,UAAWO,mBAAmB;wBAAK;mCAAM1D,gBAAgBuD,cAAcmB,UAAU;;wBAAG;mCAAMtE,mBAAmBuB;;;oBAEzI;;wBAAO;4BACL6B,MAAAA;4BACAE,qBAAAA;4BACAD,qBAAAA;4BACAkB,OAAO,SAAPA;;;;;;;gCAAoB;;wBACtB;;;;IACF"}
|
package/dist/cjs/setup/stdio.js
CHANGED
|
@@ -159,7 +159,7 @@ function _unsupported_iterable_to_array(o, minLen) {
|
|
|
159
159
|
if (typeof o === "string") return _array_like_to_array(o, minLen);
|
|
160
160
|
var n = Object.prototype.toString.call(o).slice(8, -1);
|
|
161
161
|
if (n === "Object" && o.constructor) n = o.constructor.name;
|
|
162
|
-
if (n === "Map" || n === "Set") return Array.from(
|
|
162
|
+
if (n === "Map" || n === "Set") return Array.from(o);
|
|
163
163
|
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
|
|
164
164
|
}
|
|
165
165
|
function createStdioServer(config, overrides) {
|
|
@@ -200,21 +200,15 @@ function _unsupported_iterable_to_array(o, minLen) {
|
|
|
200
200
|
if (typeof o === "string") return _array_like_to_array(o, minLen);
|
|
201
201
|
var n = Object.prototype.toString.call(o).slice(8, -1);
|
|
202
202
|
if (n === "Object" && o.constructor) n = o.constructor.name;
|
|
203
|
-
if (n === "Map" || n === "Set") return Array.from(
|
|
203
|
+
if (n === "Map" || n === "Set") return Array.from(o);
|
|
204
204
|
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
|
|
205
205
|
}
|
|
206
206
|
function discoverHeader(sheets, spreadsheetId, sheetTitle) {
|
|
207
207
|
return _async_to_generator(function() {
|
|
208
|
-
var _response_data, response
|
|
208
|
+
var _response_data, response;
|
|
209
209
|
return _ts_generator(this, function(_state) {
|
|
210
210
|
switch(_state.label){
|
|
211
211
|
case 0:
|
|
212
|
-
_state.trys.push([
|
|
213
|
-
0,
|
|
214
|
-
2,
|
|
215
|
-
,
|
|
216
|
-
3
|
|
217
|
-
]);
|
|
218
212
|
return [
|
|
219
213
|
4,
|
|
220
214
|
sheets.spreadsheets.values.get({
|
|
@@ -229,16 +223,6 @@ function discoverHeader(sheets, spreadsheetId, sheetTitle) {
|
|
|
229
223
|
2,
|
|
230
224
|
(((_response_data = response.data) === null || _response_data === void 0 ? void 0 : _response_data.values) || [])[0] || []
|
|
231
225
|
];
|
|
232
|
-
case 2:
|
|
233
|
-
unused = _state.sent();
|
|
234
|
-
return [
|
|
235
|
-
2,
|
|
236
|
-
[]
|
|
237
|
-
];
|
|
238
|
-
case 3:
|
|
239
|
-
return [
|
|
240
|
-
2
|
|
241
|
-
];
|
|
242
226
|
}
|
|
243
227
|
});
|
|
244
228
|
})();
|