Skip to main content
Glama
ricleedo

Google Services MCP Server

by ricleedo

distance-matrix

Calculate travel distance and time between multiple origins and destinations using Google Maps data for driving, walking, bicycling, or transit modes.

Instructions

Calculate travel distance and time between multiple origins and destinations

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
originsYesArray of origin locations
destinationsYesArray of destination locations
modeNoTravel mode

Implementation Reference

  • The main handler function for the 'distance-matrix' tool. It uses the Google Maps Distance Matrix API to compute distances and durations between multiple origins and destinations, formats the results into markdown using a helper function, and returns them.
    export async function distanceMatrix(
      params: z.infer<typeof distanceMatrixSchema>,
      extra?: any
    ) {
      const apiKey = process.env.GOOGLE_MAPS_API_KEY;
      if (!apiKey) {
        throw new Error("GOOGLE_MAPS_API_KEY is required");
      }
    
      try {
        const response = await googleMapsClient.distancematrix({
          params: {
            origins: params.origins,
            destinations: params.destinations,
            mode: (params.mode || "driving") as any,
            key: apiKey,
          },
        });
    
        const rows = response.data.rows;
        const results = [];
    
        for (let i = 0; i < params.origins.length; i++) {
          for (let j = 0; j < params.destinations.length; j++) {
            const element = rows[i].elements[j];
            results.push({
              origin: params.origins[i],
              destination: params.destinations[j],
              distance: element.distance?.text || "N/A",
              duration: element.duration?.text || "N/A",
              status: element.status,
            });
          }
        }
    
        return {
          content: [
            {
              type: "text" as const,
              text: formatDistanceMatrixToMarkdown(results),
            },
          ],
        };
      } catch (error) {
        return {
          content: [
            {
              type: "text" as const,
              text: `Error calculating distance matrix: ${
                error instanceof Error ? error.message : String(error)
              }`,
            },
          ],
        };
      }
    }
  • Zod schema defining the input parameters for the distance-matrix tool: origins (array of strings), destinations (array of strings), and optional mode (driving, walking, etc.).
    export const distanceMatrixSchema = z.object({
      origins: z.array(z.string()).describe("Array of origin locations"),
      destinations: z.array(z.string()).describe("Array of destination locations"),
      mode: z
        .enum(["driving", "walking", "bicycling", "transit"])
        .optional()
        .describe("Travel mode"),
    });
  • src/index.ts:100-107 (registration)
    Registration of the 'distance-matrix' tool on the MCP server, linking the name, description, schema, and handler function.
    server.tool(
      "distance-matrix",
      "Calculate travel distance and time between multiple origins and destinations",
      distanceMatrixSchema.shape,
      async (params) => {
        return await distanceMatrix(params);
      }
    );
  • Helper function to format the distance matrix results into a markdown table-like structure for the response.
    function formatDistanceMatrixToMarkdown(results: any[]): string {
      let markdown = `# Distance Matrix Results\n\n`;
      
      results.forEach((result, index) => {
        markdown += `## ${index + 1}. ${result.origin} → ${result.destination}\n`;
        markdown += `Distance: ${result.distance}  \n`;
        markdown += `Duration: ${result.duration}  \n`;
        markdown += `Status: ${result.status}  \n\n`;
      });
      
      return markdown;
    }
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions calculation but doesn't describe whether this is a read-only operation, what data sources it uses (e.g., real-time traffic), rate limits, authentication needs, or what happens with invalid inputs. This leaves significant behavioral gaps for a tool with potential external dependencies.

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 a single, efficient sentence that directly states the tool's function without unnecessary words. It's appropriately sized and front-loaded with the core purpose, making it easy to parse quickly.

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?

For a tool with no annotations, no output schema, and parameters that likely interact with external services, the description is insufficient. It doesn't cover return values (e.g., matrix format, units), error conditions, or practical constraints like API limits, leaving the agent with incomplete context for reliable use.

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?

The description adds minimal semantic value beyond the input schema, which has 100% coverage with clear descriptions for all parameters. It implies the tool handles multiple origins and destinations but doesn't explain format expectations (e.g., addresses vs. coordinates), constraints (e.g., array size limits), or how the calculation works across combinations.

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 verb 'calculate' and the resources 'travel distance and time between multiple origins and destinations', making the purpose specific and understandable. However, it doesn't explicitly differentiate from sibling tools like 'get-directions' or 'geocode', which prevents a perfect score.

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 like 'get-directions' or 'geocode', nor does it mention prerequisites or exclusions. It simply states what the tool does without contextual usage information.

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/ricleedo/Google-Service-MCP'

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