Skip to main content
Glama
krzko

Google Cloud MCP Server

by krzko

Query Logs by Time Range

gcp-logging-query-time-range

Query Google Cloud Logs within specific time ranges using relative times or ISO timestamps to retrieve and filter log entries for analysis.

Instructions

Query Google Cloud Logs within a specific time range. Supports relative times (1h, 2d) and ISO timestamps.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
startTimeYesStart time in ISO format or relative time (e.g., "1h", "2d")
endTimeNoEnd time in ISO format (defaults to now)
filterNoAdditional filter criteria
limitNoMaximum number of log entries to return

Implementation Reference

  • The main handler function for the 'gcp-logging-query-time-range' tool. It parses the start and end times, constructs a timestamp filter, queries the GCP Logging API, formats the log entries, and returns the results or handles errors gracefully.
        async ({ startTime, endTime, filter, limit }) => {
          try {
            const projectId = await getProjectId();
            const logging = getLoggingClient();
    
            const start = parseRelativeTime(startTime);
            const end = endTime ? parseRelativeTime(endTime) : new Date();
    
            // Build filter string
            let filterStr = `timestamp >= "${start.toISOString()}" AND timestamp <= "${end.toISOString()}"`;
            if (filter) {
              filterStr = `${filterStr} AND ${filter}`;
            }
    
            const [entries] = await logging.getEntries({
              pageSize: limit,
              filter: filterStr,
            });
    
            if (!entries || entries.length === 0) {
              return {
                content: [
                  {
                    type: "text",
                    text: `No log entries found in the specified time range with filter: ${filterStr}`,
                  },
                ],
              };
            }
    
            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 Time Range Results\n\nProject: ${projectId}\nTime Range: ${start.toISOString()} to ${end.toISOString()}\nFilter: ${filter || "None"}\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 time range format and try again. Valid formats include:
    - ISO date strings (e.g., "2025-03-01T00:00:00Z")
    - Relative time expressions: "1h" (1 hour ago), "2d" (2 days ago), "1w" (1 week ago), etc.`,
                },
              ],
              isError: true,
            };
          }
        },
  • Zod schema for the tool's input parameters: startTime (required), endTime (optional), filter (optional), and limit (with defaults).
    inputSchema: {
      startTime: z
        .string()
        .describe(
          'Start time in ISO format or relative time (e.g., "1h", "2d")',
        ),
      endTime: z
        .string()
        .optional()
        .describe("End time in ISO format (defaults to now)"),
      filter: z.string().optional().describe("Additional filter criteria"),
      limit: z
        .number()
        .min(1)
        .max(1000)
        .default(50)
        .describe("Maximum number of log entries to return"),
    },
  • Registration of the 'gcp-logging-query-time-range' tool with the MCP server inside the registerLoggingTools function.
        "gcp-logging-query-time-range",
        {
          title: "Query Logs by Time Range",
          description:
            "Query Google Cloud Logs within a specific time range. Supports relative times (1h, 2d) and ISO timestamps.",
          inputSchema: {
            startTime: z
              .string()
              .describe(
                'Start time in ISO format or relative time (e.g., "1h", "2d")',
              ),
            endTime: z
              .string()
              .optional()
              .describe("End time in ISO format (defaults to now)"),
            filter: z.string().optional().describe("Additional filter criteria"),
            limit: z
              .number()
              .min(1)
              .max(1000)
              .default(50)
              .describe("Maximum number of log entries to return"),
          },
        },
        async ({ startTime, endTime, filter, limit }) => {
          try {
            const projectId = await getProjectId();
            const logging = getLoggingClient();
    
            const start = parseRelativeTime(startTime);
            const end = endTime ? parseRelativeTime(endTime) : new Date();
    
            // Build filter string
            let filterStr = `timestamp >= "${start.toISOString()}" AND timestamp <= "${end.toISOString()}"`;
            if (filter) {
              filterStr = `${filterStr} AND ${filter}`;
            }
    
            const [entries] = await logging.getEntries({
              pageSize: limit,
              filter: filterStr,
            });
    
            if (!entries || entries.length === 0) {
              return {
                content: [
                  {
                    type: "text",
                    text: `No log entries found in the specified time range with filter: ${filterStr}`,
                  },
                ],
              };
            }
    
            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 Time Range Results\n\nProject: ${projectId}\nTime Range: ${start.toISOString()} to ${end.toISOString()}\nFilter: ${filter || "None"}\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 time range format and try again. Valid formats include:
    - ISO date strings (e.g., "2025-03-01T00:00:00Z")
    - Relative time expressions: "1h" (1 hour ago), "2d" (2 days ago), "1w" (1 week ago), etc.`,
                },
              ],
              isError: true,
            };
          }
        },
      );
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. While it mentions time range support, it doesn't describe what the tool returns (log entries format, structure), whether it's paginated, rate limits, authentication requirements, or error handling. For a query tool with no annotations, this leaves significant behavioral gaps.

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

Conciseness5/5

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

The description is extremely concise - just two sentences that directly state the tool's core functionality and parameter format support. Every word earns its place with zero waste or redundancy. It's appropriately sized for a straightforward query tool.

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 has no annotations and no output schema, the description is insufficiently complete. It doesn't explain what the tool returns (log entries, their structure, or format), doesn't mention pagination behavior despite having a limit parameter, and provides no context about authentication or error handling. For a query tool with 4 parameters and no structured output documentation, this leaves too many gaps.

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%, so the schema already fully documents all four parameters. The description adds minimal value by mentioning 'relative times (1h, 2d) and ISO timestamps,' which is already covered in the schema descriptions for startTime and endTime. No additional parameter semantics are provided beyond what's in the schema.

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 as 'Query Google Cloud Logs within a specific time range,' which is a specific verb+resource combination. However, it doesn't distinguish this tool from its sibling 'gcp-logging-query-logs' or 'gcp-logging-search-comprehensive,' which appear to be related logging tools. The description is clear but 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 mentions time range support but doesn't explain when this tool is preferred over 'gcp-logging-query-logs' or other logging siblings. There's no mention of prerequisites, exclusions, or comparative context with other tools.

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