Skip to main content
Glama
krzko

Google Cloud MCP Server

by krzko

Query Logs

gcp-logging-query-logs

Query Google Cloud Logs using custom filters to search across all payload types and metadata fields. Retrieve log entries with specified limits for monitoring and troubleshooting.

Instructions

Query Google Cloud Logs with custom filters. Searches across all payload types (text, JSON, proto) and metadata fields.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filterYesThe filter to apply to logs (Cloud Logging query language)
limitNoMaximum number of log entries to return

Implementation Reference

  • The complete implementation of the 'gcp-logging-query-logs' tool, including inline Zod schema for input validation (filter and limit), the handler logic that uses getProjectId, getLoggingClient to query logs via logging.getEntries, formats results with formatLogEntry, and returns markdown-formatted content or error.
      server.registerTool(
        "gcp-logging-query-logs",
        {
          title: "Query Logs",
          description:
            "Query Google Cloud Logs with custom filters. Searches across all payload types (text, JSON, proto) and metadata fields.",
          inputSchema: {
            filter: z
              .string()
              .describe(
                "The filter to apply to logs (Cloud Logging query language)",
              ),
            limit: z
              .number()
              .min(1)
              .max(1000)
              .default(50)
              .describe("Maximum number of log entries to return"),
          },
        },
        async ({ filter, limit }) => {
          try {
            const projectId = await getProjectId();
            const logging = getLoggingClient();
    
            const [entries] = await logging.getEntries({
              pageSize: limit,
              filter,
            });
    
            if (!entries || entries.length === 0) {
              return {
                content: [
                  {
                    type: "text",
                    text: `No log entries found matching filter: ${filter}`,
                  },
                ],
              };
            }
    
            const formattedLogs = entries
              .map((entry) => {
                try {
                  return formatLogEntry(entry as unknown as LogEntry);
                } catch (err: unknown) {
                  const errorMessage =
                    err instanceof Error ? err.message : "Unknown error";
                  return `## Error Formatting Log Entry\n\nAn error occurred while formatting a log entry: ${errorMessage}`;
                }
              })
              .join("\n\n");
    
            return {
              content: [
                {
                  type: "text",
                  text: `# Log Query Results\n\nProject: ${projectId}\nFilter: ${filter}\nEntries: ${entries.length}\n\n${formattedLogs}`,
                },
              ],
            };
          } catch (error: unknown) {
            const errorMessage =
              error instanceof Error ? error.message : "Unknown error";
    
            // Return a user-friendly error message instead of throwing
            return {
              content: [
                {
                  type: "text",
                  text: `# Error Querying Logs
    
    An error occurred while querying logs: ${errorMessage}
    
    Please check your filter syntax and try again. For filter syntax help, see: https://cloud.google.com/logging/docs/view/logging-query-language`,
                },
              ],
              isError: true,
            };
          }
        },
      );
  • src/index.ts:159-160 (registration)
    Top-level registration of logging tools by calling registerLoggingTools(server), which includes the 'gcp-logging-query-logs' tool.
    registerLoggingResources(server);
    registerLoggingTools(server);
  • Helper function getLoggingClient() that creates and returns the Google Cloud Logging client instance used in the tool handler.
    export function getLoggingClient(): Logging {
      return new Logging({
        projectId: process.env.GOOGLE_CLOUD_PROJECT,
      });
    }
  • Helper function formatLogEntry() that converts a raw LogEntry into a detailed markdown-formatted string, extracting and displaying timestamp, severity, resource, metadata, HTTP details, labels, payload, etc. Used to format query results.
    export function formatLogEntry(entry: LogEntry): string {
      // Safely format the timestamp
      let timestamp: string;
      try {
        if (!entry.timestamp) {
          timestamp = "No timestamp";
        } else {
          const date = new Date(entry.timestamp);
          timestamp = !isNaN(date.getTime())
            ? date.toISOString()
            : String(entry.timestamp);
        }
      } catch {
        timestamp = String(entry.timestamp || "Invalid timestamp");
      }
    
      const severity = entry.severity || "DEFAULT";
      const resourceType = entry.resource?.type || "unknown";
      const resourceLabels = entry.resource?.labels
        ? Object.entries(entry.resource.labels)
            .map(([k, v]) => `${k}=${v}`)
            .join(", ")
        : "";
    
      const resource = resourceLabels
        ? `${resourceType}(${resourceLabels})`
        : resourceType;
    
      // Start building the comprehensive log entry display
      let result = `## ${timestamp} | ${severity} | ${resource}\n\n`;
    
      // Basic metadata
      if (entry.logName) result += `**Log Name:** ${entry.logName}\n`;
      if (entry.insertId) result += `**Insert ID:** ${entry.insertId}\n`;
      if (entry.receiveTimestamp) {
        try {
          const receiveTime = new Date(entry.receiveTimestamp).toISOString();
          result += `**Receive Time:** ${receiveTime}\n`;
        } catch {
          result += `**Receive Time:** ${entry.receiveTimestamp}\n`;
        }
      }
    
      // Trace context information
      if (entry.trace) result += `**Trace:** ${entry.trace}\n`;
      if (entry.spanId) result += `**Span ID:** ${entry.spanId}\n`;
      if (entry.traceSampled !== undefined)
        result += `**Trace Sampled:** ${entry.traceSampled}\n`;
    
      // Source location if available
      if (entry.sourceLocation) {
        result += `**Source Location:**\n`;
        if (entry.sourceLocation.file)
          result += `  - File: ${entry.sourceLocation.file}\n`;
        if (entry.sourceLocation.line)
          result += `  - Line: ${entry.sourceLocation.line}\n`;
        if (entry.sourceLocation.function)
          result += `  - Function: ${entry.sourceLocation.function}\n`;
      }
    
      // HTTP request details if available
      if (entry.httpRequest) {
        result += `**HTTP Request:**\n`;
        if (entry.httpRequest.requestMethod)
          result += `  - Method: ${entry.httpRequest.requestMethod}\n`;
        if (entry.httpRequest.requestUrl)
          result += `  - URL: ${entry.httpRequest.requestUrl}\n`;
        if (entry.httpRequest.status)
          result += `  - Status: ${entry.httpRequest.status}\n`;
        if (entry.httpRequest.userAgent)
          result += `  - User Agent: ${entry.httpRequest.userAgent}\n`;
        if (entry.httpRequest.remoteIp)
          result += `  - Remote IP: ${entry.httpRequest.remoteIp}\n`;
        if (entry.httpRequest.latency)
          result += `  - Latency: ${entry.httpRequest.latency}\n`;
        if (entry.httpRequest.requestSize)
          result += `  - Request Size: ${entry.httpRequest.requestSize}\n`;
        if (entry.httpRequest.responseSize)
          result += `  - Response Size: ${entry.httpRequest.responseSize}\n`;
        if (entry.httpRequest.referer)
          result += `  - Referer: ${entry.httpRequest.referer}\n`;
        if (entry.httpRequest.protocol)
          result += `  - Protocol: ${entry.httpRequest.protocol}\n`;
        if (entry.httpRequest.cacheHit !== undefined)
          result += `  - Cache Hit: ${entry.httpRequest.cacheHit}\n`;
        if (entry.httpRequest.cacheLookup !== undefined)
          result += `  - Cache Lookup: ${entry.httpRequest.cacheLookup}\n`;
        if (entry.httpRequest.cacheValidatedWithOriginServer !== undefined) {
          result += `  - Cache Validated: ${entry.httpRequest.cacheValidatedWithOriginServer}\n`;
        }
        if (entry.httpRequest.cacheFillBytes)
          result += `  - Cache Fill Bytes: ${entry.httpRequest.cacheFillBytes}\n`;
      }
    
      // Operation details if available
      if (entry.operation) {
        result += `**Operation:**\n`;
        if (entry.operation.id) result += `  - ID: ${entry.operation.id}\n`;
        if (entry.operation.producer)
          result += `  - Producer: ${entry.operation.producer}\n`;
        if (entry.operation.first !== undefined)
          result += `  - First: ${entry.operation.first}\n`;
        if (entry.operation.last !== undefined)
          result += `  - Last: ${entry.operation.last}\n`;
      }
    
      // Labels if they exist
      if (entry.labels && Object.keys(entry.labels).length > 0) {
        try {
          result += `**Labels:**\n`;
          Object.entries(entry.labels).forEach(([key, value]) => {
            result += `  - ${key}: ${value}\n`;
          });
        } catch (error: unknown) {
          const errorMessage =
            error instanceof Error ? error.message : "Unknown error";
          result += `**Labels:** [Error formatting labels: ${errorMessage}]\n`;
        }
      }
    
      // Add any additional fields that might be present
      const knownFields = new Set([
        "timestamp",
        "severity",
        "resource",
        "logName",
        "textPayload",
        "jsonPayload",
        "protoPayload",
        "labels",
        "insertId",
        "trace",
        "spanId",
        "traceSampled",
        "sourceLocation",
        "httpRequest",
        "operation",
        "receiveTimestamp",
      ]);
    
      const additionalFields: Record<string, unknown> = {};
      Object.entries(entry).forEach(([key, value]) => {
        if (!knownFields.has(key) && value !== undefined && value !== null) {
          additionalFields[key] = value;
        }
      });
    
      if (Object.keys(additionalFields).length > 0) {
        result += `**Additional Fields:**\n`;
        try {
          result += `\`\`\`json\n${JSON.stringify(additionalFields, null, 2)}\n\`\`\`\n`;
        } catch (error: unknown) {
          const errorMessage =
            error instanceof Error ? error.message : "Unknown error";
          result += `[Error formatting additional fields: ${errorMessage}]\n`;
        }
      }
    
      // Format the main payload
      result += `\n**Payload:**\n`;
      try {
        if (entry.textPayload !== undefined && entry.textPayload !== null) {
          result += `\`\`\`\n${String(entry.textPayload)}\n\`\`\``;
        } else if (entry.jsonPayload) {
          result += `\`\`\`json\n${JSON.stringify(entry.jsonPayload, null, 2)}\n\`\`\``;
        } else if (entry.protoPayload) {
          result += `\`\`\`json\n${JSON.stringify(entry.protoPayload, null, 2)}\n\`\`\``;
        } else {
          // Check for any other payload-like fields
          const data = entry.data || entry.message || entry.msg;
          if (data) {
            if (typeof data === "string") {
              result += `\`\`\`\n${data}\n\`\`\``;
            } else {
              result += `\`\`\`json\n${JSON.stringify(data, null, 2)}\n\`\`\``;
            }
          } else {
            result += `\`\`\`\n[No payload available]\n\`\`\``;
          }
        }
      } catch (error: unknown) {
        const errorMessage =
          error instanceof Error ? error.message : "Unknown error";
        result += `\`\`\`\n[Error formatting payload: ${errorMessage}]\n\`\`\``;
      }
    
      return result;
    }
  • Zod input schema defining the tool parameters: filter (string, Cloud Logging query language) and limit (number, 1-1000, default 50).
      inputSchema: {
        filter: z
          .string()
          .describe(
            "The filter to apply to logs (Cloud Logging query language)",
          ),
        limit: z
          .number()
          .min(1)
          .max(1000)
          .default(50)
          .describe("Maximum number of log entries to return"),
      },
    },
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions searching across payload types and metadata fields, which adds some context about the tool's scope. However, it lacks critical details such as authentication requirements, rate limits, pagination behavior, error handling, or the format of returned results. For a query tool with no annotation coverage, this is a significant gap in transparency.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is concise and front-loaded, consisting of two sentences that directly state the tool's purpose and scope. There is no unnecessary information, and each sentence contributes to understanding the tool's functionality. However, it could be slightly improved by integrating usage guidance without adding verbosity.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (querying logs with custom filters), lack of annotations, and absence of an output schema, the description is incomplete. It does not cover behavioral aspects like authentication, rate limits, or result format, and it fails to differentiate from sibling tools. For a query operation in a cloud environment, more context is needed to ensure proper agent usage.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, meaning the input schema fully documents the 'filter' and 'limit' parameters. The description adds minimal value beyond the schema by implying the filter uses 'custom filters' and searches across payload types, but it does not provide additional syntax, examples, or constraints. With high schema coverage, the baseline score of 3 is appropriate as the description does not significantly enhance parameter understanding.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Query Google Cloud Logs with custom filters.' It specifies the verb ('Query'), resource ('Google Cloud Logs'), and scope ('custom filters'), and mentions searching across payload types and metadata fields. However, it does not explicitly differentiate from sibling tools like 'gcp-logging-query-time-range' or 'gcp-logging-search-comprehensive', which may have overlapping functionality, so it lacks sibling differentiation.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It does not mention sibling tools such as 'gcp-logging-query-time-range' or 'gcp-logging-search-comprehensive', nor does it specify prerequisites, contexts, or exclusions for usage. This leaves the agent without clear direction on tool selection.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/krzko/google-cloud-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server