|
| 1 | +import { z } from "zod"; |
| 2 | + |
| 3 | +import { tool } from "../../tool"; |
| 4 | +import { mcpError, toContent } from "../../util"; |
| 5 | +import { getApiFilter } from "../../../functions/functionslog"; |
| 6 | +import { listEntries } from "../../../gcp/cloudlogging"; |
| 7 | + |
| 8 | +const SEVERITY_LEVELS = [ |
| 9 | + "DEFAULT", |
| 10 | + "DEBUG", |
| 11 | + "INFO", |
| 12 | + "NOTICE", |
| 13 | + "WARNING", |
| 14 | + "ERROR", |
| 15 | + "CRITICAL", |
| 16 | + "ALERT", |
| 17 | + "EMERGENCY", |
| 18 | +] as const; |
| 19 | + |
| 20 | +// normalizeFunctionSelectors standardizes tool input into the comma-separated |
| 21 | +// list that the existing logging filter helper expects (matching CLI behaviour). |
| 22 | +function normalizeFunctionSelectors(selectors?: string | string[]): string | undefined { |
| 23 | + if (!selectors) return undefined; |
| 24 | + if (Array.isArray(selectors)) { |
| 25 | + const cleaned = selectors.map((name) => name.trim()).filter(Boolean); |
| 26 | + return cleaned.length ? cleaned.join(",") : undefined; |
| 27 | + } |
| 28 | + const cleaned = selectors |
| 29 | + .split(/[,\s]+/) |
| 30 | + .map((name) => name.trim()) |
| 31 | + .filter(Boolean); |
| 32 | + return cleaned.length ? cleaned.join(",") : undefined; |
| 33 | +} |
| 34 | + |
| 35 | +function validateTimestamp(label: string, value: string): string | null { |
| 36 | + const parsed = Date.parse(value); |
| 37 | + if (Number.isNaN(parsed)) { |
| 38 | + return `${label} must be an RFC3339/ISO 8601 timestamp, received '${value}'.`; |
| 39 | + } |
| 40 | + return null; |
| 41 | +} |
| 42 | + |
| 43 | +export const get_logs = tool( |
| 44 | + { |
| 45 | + name: "get_logs", |
| 46 | + description: |
| 47 | + "Retrieves a page of Cloud Functions log entries using Google Cloud Logging advanced filters.", |
| 48 | + inputSchema: z.object({ |
| 49 | + function_names: z |
| 50 | + .union([z.string(), z.array(z.string()).min(1)]) |
| 51 | + .optional() |
| 52 | + .describe( |
| 53 | + "Optional list of deployed Cloud Function names to filter logs (string or array).", |
| 54 | + ), |
| 55 | + page_size: z |
| 56 | + .number() |
| 57 | + .int() |
| 58 | + .min(1) |
| 59 | + .max(1000) |
| 60 | + .default(50) |
| 61 | + .describe("Maximum number of log entries to return."), |
| 62 | + order: z.enum(["asc", "desc"]).default("desc").describe("Sort order by timestamp"), |
| 63 | + page_token: z |
| 64 | + .string() |
| 65 | + .optional() |
| 66 | + .describe("Opaque page token returned from a previous call to continue pagination."), |
| 67 | + min_severity: z |
| 68 | + .enum(SEVERITY_LEVELS) |
| 69 | + .optional() |
| 70 | + .describe("Filters results to entries at or above the provided severity level."), |
| 71 | + start_time: z |
| 72 | + .string() |
| 73 | + .optional() |
| 74 | + .describe( |
| 75 | + "RFC3339 timestamp (YYYY-MM-DDTHH:MM:SSZ). Only entries with timestamp greater than or equal to this are returned.", |
| 76 | + ), |
| 77 | + end_time: z |
| 78 | + .string() |
| 79 | + .optional() |
| 80 | + .describe( |
| 81 | + "RFC3339 timestamp (YYYY-MM-DDTHH:MM:SSZ). Only entries with timestamp less than or equal to this are returned.", |
| 82 | + ), |
| 83 | + filter: z |
| 84 | + .string() |
| 85 | + .optional() |
| 86 | + .describe( |
| 87 | + "Additional Google Cloud Logging advanced filter text that will be AND'ed with the generated filter.", |
| 88 | + ), |
| 89 | + }), |
| 90 | + annotations: { |
| 91 | + title: "Get Functions Logs from Cloud Logging", |
| 92 | + readOnlyHint: true, |
| 93 | + openWorldHint: true, |
| 94 | + }, |
| 95 | + _meta: { |
| 96 | + requiresAuth: true, |
| 97 | + requiresProject: true, |
| 98 | + }, |
| 99 | + }, |
| 100 | + async ( |
| 101 | + { function_names, page_size, order, page_token, min_severity, start_time, end_time, filter }, |
| 102 | + { projectId }, |
| 103 | + ) => { |
| 104 | + const resolvedOrder = order; |
| 105 | + const resolvedPageSize = page_size; |
| 106 | + |
| 107 | + const normalizedSelectors = normalizeFunctionSelectors(function_names); |
| 108 | + const filterParts: string[] = [getApiFilter(normalizedSelectors)]; |
| 109 | + |
| 110 | + if (min_severity) { |
| 111 | + filterParts.push(`severity>="${min_severity}"`); |
| 112 | + } |
| 113 | + if (start_time) { |
| 114 | + const error = validateTimestamp("start_time", start_time); |
| 115 | + if (error) return mcpError(error); |
| 116 | + filterParts.push(`timestamp>="${start_time}"`); |
| 117 | + } |
| 118 | + if (end_time) { |
| 119 | + const error = validateTimestamp("end_time", end_time); |
| 120 | + if (error) return mcpError(error); |
| 121 | + filterParts.push(`timestamp<="${end_time}"`); |
| 122 | + } |
| 123 | + if (start_time && end_time && Date.parse(start_time) > Date.parse(end_time)) { |
| 124 | + return mcpError("start_time must be less than or equal to end_time."); |
| 125 | + } |
| 126 | + if (filter) { |
| 127 | + filterParts.push(`(${filter})`); |
| 128 | + } |
| 129 | + |
| 130 | + const combinedFilter = filterParts.join("\n"); |
| 131 | + |
| 132 | + try { |
| 133 | + const { entries, nextPageToken } = await listEntries( |
| 134 | + projectId, |
| 135 | + combinedFilter, |
| 136 | + resolvedPageSize, |
| 137 | + resolvedOrder, |
| 138 | + page_token, |
| 139 | + ); |
| 140 | + |
| 141 | + const formattedEntries = entries.map((entry) => { |
| 142 | + const functionName = |
| 143 | + entry.resource?.labels?.function_name ?? entry.resource?.labels?.service_name ?? null; |
| 144 | + const payload = |
| 145 | + entry.textPayload ?? entry.jsonPayload ?? entry.protoPayload ?? entry.labels ?? null; |
| 146 | + return { |
| 147 | + timestamp: entry.timestamp ?? entry.receiveTimestamp ?? null, |
| 148 | + severity: entry.severity ?? "DEFAULT", |
| 149 | + function: functionName, |
| 150 | + message: |
| 151 | + entry.textPayload ?? |
| 152 | + (entry.jsonPayload ? JSON.stringify(entry.jsonPayload) : undefined) ?? |
| 153 | + (entry.protoPayload ? JSON.stringify(entry.protoPayload) : undefined) ?? |
| 154 | + "", |
| 155 | + payload, |
| 156 | + log_name: entry.logName, |
| 157 | + trace: entry.trace ?? null, |
| 158 | + span_id: entry.spanId ?? null, |
| 159 | + }; |
| 160 | + }); |
| 161 | + |
| 162 | + const response = { |
| 163 | + filter: combinedFilter, |
| 164 | + order: resolvedOrder, |
| 165 | + page_size: resolvedPageSize, |
| 166 | + entries: resolvedOrder === "asc" ? formattedEntries : formattedEntries.reverse(), |
| 167 | + next_page_token: nextPageToken ?? null, |
| 168 | + has_more: Boolean(nextPageToken), |
| 169 | + }; |
| 170 | + |
| 171 | + if (!entries.length) { |
| 172 | + return toContent(response, { |
| 173 | + contentPrefix: "No log entries matched the provided filters.\n\n", |
| 174 | + }); |
| 175 | + } |
| 176 | + |
| 177 | + return toContent(response); |
| 178 | + } catch (err) { |
| 179 | + const message = |
| 180 | + err instanceof Error ? err.message : "Failed to retrieve Cloud Logging entries."; |
| 181 | + return mcpError(message); |
| 182 | + } |
| 183 | + }, |
| 184 | +); |
0 commit comments