diff --git a/packages/maps-grounding-essentials/.gitignore b/packages/maps-grounding-essentials/.gitignore new file mode 100644 index 0000000..f450c14 --- /dev/null +++ b/packages/maps-grounding-essentials/.gitignore @@ -0,0 +1,37 @@ +# Dependencies +node_modules/ + +# Build outputs +dist/ +*.zip + +# System files +.DS_Store +Thumbs.db + +# IDE files +.vscode/ +.idea/ +*.swp +*.swo + +# Environment variables +.env +.env.local +.env.*.local + +# Logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* + +# Test coverage +coverage/ +.nyc_output/ + +# Temporary files +*.tmp +.temp/ +tmp/ \ No newline at end of file diff --git a/packages/maps-grounding-essentials/CHANGELOG.md b/packages/maps-grounding-essentials/CHANGELOG.md new file mode 100644 index 0000000..6361e43 --- /dev/null +++ b/packages/maps-grounding-essentials/CHANGELOG.md @@ -0,0 +1,3 @@ +# Changelog + +All notable changes to this project will be documented in this file. diff --git a/packages/maps-grounding-essentials/CONTRIBUTING.md b/packages/maps-grounding-essentials/CONTRIBUTING.md new file mode 100644 index 0000000..1426e1e --- /dev/null +++ b/packages/maps-grounding-essentials/CONTRIBUTING.md @@ -0,0 +1,3 @@ +# How to contribute + +Please see the main [CONTRIBUTING.md](../../CONTRIBUTING.md) for contribution guidelines. diff --git a/packages/maps-grounding-essentials/LICENSE b/packages/maps-grounding-essentials/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/packages/maps-grounding-essentials/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/maps-grounding-essentials/README.md b/packages/maps-grounding-essentials/README.md new file mode 100644 index 0000000..e8ccbc8 --- /dev/null +++ b/packages/maps-grounding-essentials/README.md @@ -0,0 +1,239 @@ +[![npm](https://img.shields.io/npm/v/@googlemaps/maps-grounding-essentials-mcp)][npm-pkg] +![Alpha](https://img.shields.io/badge/release-alpha-orange) +[![License](https://img.shields.io/github/license/googlemaps/platform-ai?color=blue)][license] +[![Discord](https://img.shields.io/discord/676948200904589322?color=6A7EC2&logo=discord&logoColor=ffffff)][Discord server] +[![Install MCP Server](https://cursor.com/deeplink/mcp-install-dark.svg)](https://cursor.com/en/install-mcp?name=google-maps-platform&config=eyJjb21tYW5kIjoibnB4IC15IEBnb29nbGVtYXBzL21hcHMtZ3JvdW5kaW5nLWVzc2VudGlhbHMtbWNwIn0) + + Try in Firebase Studio + + +# Google Maps Platform Logo Google Maps Platform Maps Grounding Essentials Toolkit +*Alpha version* + +## Description + +The Google Maps Platform Maps Grounding Essentials toolkit is a Model Context Protocol (MCP) server that provides essential Google Maps Platform functionalities, such as Places Search, Route Computation, and Weather Lookup. This toolkit enhances the responses from large language models (LLMs) used for developing applications with the Google Maps Platform by giving them direct access to these functionalities. + +Since the MCP server accesses the content when the model is prompted, the LLM's context regarding Google Maps Platform does not have to be limited to the available data at the model's training date. + +## 🔧 Tools Provided + +The MCP server exposes the following tools for AI clients: + + 1. **`GoogleMapsPlatformWeatherLookup`**: Provides current conditions, hourly, and daily forecasts for any location. + 2. **`GoogleMapsPlatformPlacesSearchText`**: Searches for places using a text query. + 3. **`GoogleMapsPlatformComputeRoutes`**: Computes a travel route between a specified origin and destination. + +----- + +## 🛠️ Supported MCP Transports + +This server supports the following standard MCP communication protocol: + + * **`stdio`**: This is the default transport used when a client invokes the server via a `command`. It communicates over the standard input/output streams, making it ideal for local command-line execution. + +----- + +## 🚀 Usage + +You can run the Maps Grounding Essentials MCP server on your local development machine. + +### Requirements + +In order to use the Google Maps Platform Maps Grounding Essentials toolkit, you need an environment with [Node.js](https://nodejs.org/en/download/) (LTS version recommended) and npm installed in order to clone and run the server, as well as an MCP client to access the server. + +### Use Maps Grounding Essentials as a Local MCP Server with `stdio` transport (Recommended) + +Run the server on your local machine and connect clients using `stdio` protocol for use with AI-assisted IDEs (like VS Code, Android Studio, Cursor) or desktop AI applications (like Gemini CLI). This is the simplest and most common setup. + +#### Configure Your Client + +Add the server to your preferred AI client's MCP configuration file. Find your client below for specific, verified instructions. + +1. **[Gemini Code Assist & Gemini CLI](https://developers.google.com/gemini-code-assist/docs/use-agentic-chat-pair-programmer#configure-mcp-servers)** + * Option 1 - Add the server directly from your command line (assuming you have Gemini CLI already installed): + ```bash + gemini mcp add google-maps-platform-maps-tool npx -y @googlemaps/maps-grounding-essentials-mcp@latest + ``` + * Verify the installation by running `gemini mcp list`. + * Option 2 - Add the MCP server config manually to your `~/.gemini/settings.json` file. + ```json + { + "mcpServers": { + "google-maps-platform-maps-tool": { + "command": "npx", + "args": ["-y", "@googlemaps/maps-grounding-essentials-mcp@latest"], + "env": { + "GOOGLE_MAPS_API_KEY": "YOUR_API_KEY" + } + } + } + } + ``` + +2. **[Claude Code](https://docs.anthropic.com/en/docs/claude-code/mcp)** + * Option 1 - Add the server directly from your command line (assuming you have Claude Code already installed): + ```bash + claude mcp add google-maps-platform-maps-tool -- npx -y @googlemaps/maps-grounding-essentials-mcp@latest + ``` + * Verify the installation by running `claude mcp list`. + * **Windows Users:** On native Windows (not WSL), you must use the `cmd /c` wrapper for `npx` commands to work correctly. + ```bash + claude mcp add google-maps-platform-maps-tool -- cmd /c "npx -y @googlemaps/maps-grounding-essentials-mcp@latest" + ``` + * Option 2 - Add the sever manually to your Claude config file `~/.claude.json` + ```json + "mcpServers": { + "google-maps-platform-maps-tool": { + "command": "npx", + "args": [ + "-y", "@googlemaps/maps-grounding-essentials-mcp@latest" + ], + "env": { + "GOOGLE_MAPS_API_KEY": "YOUR_API_KEY" + } + } + } + ``` + +3. **[Cursor](https://docs.cursor.com/en/context/mcp)** + * [![Install MCP Server](https://cursor.com/deeplink/mcp-install-dark.svg)](https://cursor.com/en/install-mcp?name=google-maps-platform&config=eyJjb21tYW5kIjoibnB4IC15IEBnb29nbGVtYXBzL21hcHMtZ3JvdW5kaW5nLWVzc2VudGlhbHMtbWNwIn0) <-- If you already have Cursor installed, click here to install Google Maps Platform Maps Grounding Essentials MCP directly. + * Otherwise, add it to your workspace's `.cursor-settings/mcp.json` file. + ```json + { + "mcpServers": { + "google-maps-platform-maps-tool": { + "command": "npx", + "args": ["-y", "@googlemaps/maps-grounding-essentials-mcp@latest"], + "env": { + "GOOGLE_MAPS_API_KEY": "YOUR_API_KEY" + } + } + } + } + ``` + +4. **[Firebase Studio](https://firebase.google.com/docs/studio/customize-workspace)** + * Try in Firebase Studio with Maps Grounding Essentials MCP installed + * Add to your project's `mcp.json` file in the `.idx` folder in your Firebase Studio workspace + ```json + { + "mcpServers": { + "google-maps-platform-maps-tool": { + "command": "npx", + "args": ["-y", "@googlemaps/maps-grounding-essentials-mcp@latest"], + "env": { + "GOOGLE_MAPS_API_KEY": "YOUR_API_KEY" + } + } + } + } + ``` + +5. **[Android Studio](https://developer.android.com/studio/gemini/add-mcp-server)** + * Create a `mcp.json` file and place it in the [configuration directory](https://developer.android.com/studio/troubleshoot#directories) of Android Studio. Add the Maps Grounding Essentials server to the list: + ```json + { + "mcpServers": { + "google-maps-platform-maps-tool": { + "command": "npx", + "args": ["-y", "@googlemaps/maps-grounding-essentials-mcp@latest"], + "env": { + "GOOGLE_MAPS_API_KEY": "YOUR_API_KEY" + } + } + } + } + ``` +6. **[Cline](https://docs.cline.bot/mcp/configuring-mcp-servers)** + * Option 1: install using the [Cline MCP GUI](https://docs.cline.bot/mcp/configuring-mcp-servers) + * Option 2: manually / programatically install using the Cline MCP config file. The config file is located at: + * **macOS:** `~/Library/Application Support/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json` + * **Windows:** `%APPDATA%/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json` + * **Linux:** `~/.config/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json` + * Add the following to your MCP configuration in `cline_mcp_settings.json`: + ```json + { + "mcpServers": { + "google-maps-platform-maps-tool": { + "command": "npx", + "args": ["-y", "@googlemaps/maps-grounding-essentials-mcp@latest"], + "env": { + "GOOGLE_MAPS_API_KEY": "YOUR_API_KEY" + }, + "alwaysAllow": [ + "GoogleMapsPlatformWeatherLookup", + "GoogleMapsPlatformPlacesSearchText", + "GoogleMapsPlatformComputeRoutes" + ] + } + } + } + ``` +7. **[Roo Code](https://docs.roocode.com/features/mcp/using-mcp-in-roo)** + * Option 1: install using the [Roo MCP GUI](https://docs.roocode.com/features/mcp/using-mcp-in-roo) + * Option 2: manually / programatically install using the Roo Code config file. The config file is located at: + * **macOS:** `~/Library/Application Support/Code/User/globalStorage/rooveterinaryinc.roo-cline/settings/mcp_settings.json` + * **Windows:** `%APPDATA%\Code\User\globalStorage\rooveterinaryinc.roo-cline\settings\mcp_settings.json` + * **Linux:** `~/.config/Code/User/globalStorage/rooveterinaryinc.roo-cline/settings/mcp_settings.json` + * Add the following to your MCP configuration in `mcp_settings.json`: + ```json + { + "mcpServers": { + "google-maps-platform-maps-tool": { + "command": "npx", + "args": ["-y", "@googlemaps/maps-grounding-essentials-mcp@latest"], + "env": { + "GOOGLE_MAPS_API_KEY": "YOUR_API_KEY" + }, + "alwaysAllow": [ + "GoogleMapsPlatformWeatherLookup", + "GoogleMapsPlatformPlacesSearchText", + "GoogleMapsPlatformComputeRoutes" + ] + } + } + } + ``` + +8. **[Microsoft Copilot](https://learn.microsoft.com/en-us/microsoft-copilot-studio/agent-extend-action-mcp)** + * When in Agent mode, Click "Tools" and then in the top header "Configure Tools" then "Install from an NPM package name" (See screenshots below) + * image + + * image + * image + * Enter pacakge name `@googlemaps/maps-grounding-essentials-mcp` and ENTER, accepting the install and using the default port 3000, then ENTER one last time to confirm the change + * image + + +9. **[Windsurf](https://docs.windsurf.com/windsurf/cascade/mcp)** + * Similar to Cursor instructions above. + +10. **[Kilo Code](https://kilocode.ai/docs/features/mcp/using-mcp-in-kilo-code)** + * Similar to the Cline and Roo Code instructions above + +----- + +## **Terms of Service** + +This toolkit provides tools to describe the use of Google Maps Platform services. Use of Google Maps Platform services is subject to the Google Maps Platform [Terms of Service](https://cloud.google.com/maps-platform/terms), however, if your billing address is in the European Economic Area, the Google Maps Platform [EEA Terms of Service](https://cloud.google.com/terms/maps-platform/eea) will apply to your use of the Services. Functionality varies by region. [Learn more](https://developers.google.com/maps/comms/eea/faq). + +This toolkit is not a Google Maps Platform Core Service. Therefore, the Google Maps Platform Terms of Service (e.g. Technical Support Services, Service Level Agreements, and Deprecation Policy) do not apply to the code in this repository or the RAG service called by it. + +## **Support** + +This toolkit is offered via an open source [license](https://github.com/googlemaps/.github/blob/master/LICENSE). It is not governed by the Google Maps Platform Support (Technical Support Services Guidelines, the SLA, or the [Deprecation Policy](https://cloud.google.com/maps-platform/terms)). However, any Google Maps Platform services used by the library remain subject to the Google Maps Platform Terms of Service. + +If you find a bug, or have a feature request, please [file an issue](https://github.com/googlemaps/platform-ai/issues/new/choose) on GitHub. If you would like to get answers to technical questions from other Google Maps Platform developers, ask through one of our [developer community channels](https://developers.google.com/maps/developer-community). If you'd like to contribute, please check the [contributing guide](https://github.com/googlemaps/.github/blob/master/CONTRIBUTING.md). + +You can also discuss this toolkit on our [Discord server](https://discord.gg/hYsWbmk). + + +[npm-pkg]: + + +[Discord server]: https://discord.gg/hYsWbmk +[license]: LICENSE diff --git a/packages/maps-grounding-essentials/config.ts b/packages/maps-grounding-essentials/config.ts new file mode 100644 index 0000000..8f565f5 --- /dev/null +++ b/packages/maps-grounding-essentials/config.ts @@ -0,0 +1,26 @@ +/** + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const GoogleMapsPlatformServiceUrl = "https://mapstools.googleapis.com/v1alpha" + + // Reads the API key from the GOOGLE_MAPS_API_KEY environment variable. +export function getGoogleMapsApiKey(): string { + const apiKey = process.env.GOOGLE_MAPS_API_KEY; + if (!apiKey) { + throw new Error('Environment variable GOOGLE_MAPS_API_KEY not found. Please set it to your Google Maps API key.'); + } + return apiKey; +} \ No newline at end of file diff --git a/packages/maps-grounding-essentials/index.ts b/packages/maps-grounding-essentials/index.ts new file mode 100644 index 0000000..fdb6593 --- /dev/null +++ b/packages/maps-grounding-essentials/index.ts @@ -0,0 +1,78 @@ +/** + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Server } from '@modelcontextprotocol/sdk/server/index.js'; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js'; +import { GoogleMapsPlatformWeatherLookup, handleGoogleMapsPlatformWeatherLookup } from './weather-lookup.js'; +import { GoogleMapsPlatformPlacesSearchText, handleGoogleMapsPlatformPlacesSearchText } from './places-search-text.js'; +import { GoogleMapsPlatformComputeRoutes, handleGoogleMapsPlatformComputeRoutes } from './routes-compute.js'; + + +export function getServer(): Server { + return new Server( + { + name: "google-maps-platform-maps-tools", + version: "0.0.1", + }, + { + capabilities: { + tools: {}, + logging: {}, + resources: {} + }, + } + ); +} + +const server = getServer(); + +// Set up request handlers +server.setRequestHandler(ListToolsRequestSchema, async () => ({ + tools: [GoogleMapsPlatformWeatherLookup, GoogleMapsPlatformPlacesSearchText, GoogleMapsPlatformComputeRoutes], +})); + +server.setRequestHandler(CallToolRequestSchema, async (request: any) => { + + if (request.params.name == "GoogleMapsPlatformWeatherLookup") { + return handleGoogleMapsPlatformWeatherLookup(request, server); + } else if (request.params.name == "GoogleMapsPlatformPlacesSearchText") { + return handleGoogleMapsPlatformPlacesSearchText(request, server); + } else if (request.params.name == "GoogleMapsPlatformComputeRoutes") { + return handleGoogleMapsPlatformComputeRoutes(request, server); + } + else { + server.sendLoggingMessage({ + level: "info", + data: `Tool not found: ${request.params.name}`, + }); + + return { + content: [{ type: 'text', text: "Invalid Tool called" }] + }; + } +}); + +async function runServer() { + const transport = new StdioServerTransport(); + await server.connect(transport); + console.info("Google Maps Platform Maps Tools MCP Server running on stdio"); +} + +runServer().catch((error) => { + console.error("Fatal error running server:", error); + process.exit(1); +}); diff --git a/packages/maps-grounding-essentials/package.json b/packages/maps-grounding-essentials/package.json new file mode 100644 index 0000000..cba2fe6 --- /dev/null +++ b/packages/maps-grounding-essentials/package.json @@ -0,0 +1,36 @@ +{ + "name": "@googlemaps/maps-grounding-essentials-mcp", + "version": "0.1.0", + "main": "dist/index.js", + "type": "module", + "bin": { + "maps-grounding-essentials-mcp": "dist/index.js" + }, + "files": [ + "dist" + ], + "scripts": { + "clean": "rm -rf dist *.js node_modules/ yarn.lock", + "compile": "tsc index.ts && shx chmod +x dist/*.js", + "build": "bun clean && bun build index.ts --outdir dist --target=node", + "build:prepare": "bun clean && bun build index.ts --outdir dist --target=node --format=cjs --minify && { echo '#!/usr/bin/env node'; cat dist/index.js; } > dist/index.js.tmp && mv dist/index.js.tmp dist/index.js && shx chmod +x dist/index.js && echo '{\"type\": \"commonjs\"}' > dist/package.json && cp README.md dist", + "start": "node dist/index.js", + "prepack": "npm run build:prepare", + "test:integration": "GOOGLE_MAPS_API_KEY=${GOOGLE_MAPS_API_KEY} bun test tests/integration.test.ts" + }, + "keywords": [], + "author": "", + "license": "ISC", + "description": "", + "dependencies": { + "@modelcontextprotocol/sdk": "^1.17.4", + "@types/node": "^22.15.18", + "axios": "^1.12.2", + "shx": "^0.4.0", + "typescript": "^5.8.3" + }, + "devDependencies": { + "@types/bun": "latest", + "bun": "1.2.18" + } +} diff --git a/packages/maps-grounding-essentials/places-search-text.ts b/packages/maps-grounding-essentials/places-search-text.ts new file mode 100644 index 0000000..3fe1bbf --- /dev/null +++ b/packages/maps-grounding-essentials/places-search-text.ts @@ -0,0 +1,160 @@ +/** + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Tool } from '@modelcontextprotocol/sdk/types.js'; +import { GoogleMapsPlatformServiceUrl, getGoogleMapsApiKey } from './config.js'; +import axios from 'axios'; +import { Server } from '@modelcontextprotocol/sdk/server/index.js'; + +export const GoogleMapsPlatformPlacesSearchText: Tool = { + name: 'GoogleMapsPlatformPlacesSearchText', + description: ` + **Tool Name:** Places Search Tool + **Core Functionality:** Searches for places based on a text query. + **Input Requirements (CRITICAL):** + * **text_query:** (string) - The primary search term (e.g., 'restaurants in New York', 'coffee shops near Golden Gate Park', 'SF MoMA'). This is the only mandatory parameter. + **Location Bias:** + To bias results to a specific area, use the 'location_bias' parameter. This is defined as a circle with a center point (latitude, longitude) and a radius in meters. + Example: {"location_bias": {"circle": {"center": {"latitude": 34.052235, "longitude": -118.243683}, "radius_meters": 5000}}} + **Location Information:** + Some location information must be available to use this tool. The location information can either be specified in the query (e.g., "pizza in New York") or in the location_bias parameter. + `, + inputSchema: { + "type": "object", + "description": "Schema for searching places based on a text query.", + "properties": { + "text_query": { + "type": "string", + "description": "The text query to search for places (e.g., 'restaurants in New York')." + }, + "language_code": { + "type": "string", + "description": "language code, indicating in which language the results should be returned, if possible. Full list can be found at https://developers.google.com/maps/faq#languagesupport." + }, + "region_code": { + "type": "string", + "description": "region code, indicating the region where results should be biased, if possible. This is specified as a Unicode country/region code (CLDR) two-character value. For example, to bias results to the United States, use 'US'." + }, + "location_bias": { + "type": "object", + "description": "location bias, to prefer results in a specified area. The location bias is an area, defined as a circle. If radius_meters is not specified, the center point is used as a point bias.", + "properties": { + "circle": { + "type": "object", + "description": "A circle defined by a center point and a radius.", + "properties": { + "center": { + "type": "object", + "description": "The center point of the circle.", + "properties": { + "latitude": { + "type": "number", + "description": "The latitude of the center point." + }, + "longitude": { + "type": "number", + "description": "The longitude of the center point." + } + }, + "required": ["latitude", "longitude"] + }, + "radius_meters": { + "type": "number", + "description": "The radius of the circle in meters." + } + }, + "required": ["center"] + }, + } + } + }, + "required": ["text_query"], + "additionalProperties": false + }, +}; + +export async function handleGoogleMapsPlatformPlacesSearchText(request: any, server: Server) { + try { + let textQuery: string = request.params.arguments?.text_query as string; + let languageCode: string | undefined = request.params.arguments?.language_code as string | undefined; + let regionCode: string | undefined = request.params.arguments?.region_code as string | undefined; + let locationBias: any | undefined = request.params.arguments?.location_bias as any | undefined; + + server.sendLoggingMessage({ + level: "info", + data: `Calling tool GoogleMapsPlatformPlacesSearchText with textQuery: ${textQuery}, languageCode: ${languageCode}, regionCode: ${regionCode}, locationBias: ${JSON.stringify(locationBias)}`, + }); + + try { + const apiKey = getGoogleMapsApiKey(); + const url = `${GoogleMapsPlatformServiceUrl}/places:searchText?key=${apiKey}`; + const params: any = { textQuery }; + if (languageCode) params.languageCode = languageCode; + if (regionCode) params.regionCode = regionCode; + if (locationBias) params.locationBias = locationBias; + + const headers = { + 'Content-Type': 'application/json' + }; + + const googleMapsPlatformServiceResponse = await axios.post( + url, + params, + { + headers + } + ); + + let mcpResponse = { + "response": { + "contexts": googleMapsPlatformServiceResponse.data + }, + "status": googleMapsPlatformServiceResponse.status.toString(), + }; + + return { + content: [{ + type: 'text', + text: JSON.stringify(mcpResponse) + }] + }; + + } catch (error: any) { + let errorMessage = ""; + if (error.response && error.response.data && error.response.data.error && error.response.data.error.message) { + errorMessage = error.response.data.error.message; + } + + server.sendLoggingMessage({ + level: "error", + data: `Error executing tool ${request.params.name}: ${error} \nErrorMessage: ${errorMessage}`, + }); + + return { + content: [{ type: 'text', text: errorMessage }] + }; + } + + } catch (error) { + server.sendLoggingMessage({ + level: "error", + data: `Error executing tool ${request.params.name}: ${error}`, + }); + return { + content: [{ type: 'text', text: JSON.stringify(error) }] + }; + } +} diff --git a/packages/maps-grounding-essentials/routes-compute.ts b/packages/maps-grounding-essentials/routes-compute.ts new file mode 100644 index 0000000..3a48a66 --- /dev/null +++ b/packages/maps-grounding-essentials/routes-compute.ts @@ -0,0 +1,184 @@ +/** + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Tool } from '@modelcontextprotocol/sdk/types.js'; +import { GoogleMapsPlatformServiceUrl, getGoogleMapsApiKey } from './config.js'; +import axios from 'axios'; +import { Server } from '@modelcontextprotocol/sdk/server/index.js'; +import { json } from 'stream/consumers'; +import { url } from 'inspector'; + +const LatLngSchema = { + "type": "object", + "description": "The latitude and longitude of the point.", + "properties": { + "latitude": { + "type": "number", + "description": "The latitude of the point." + }, + "longitude": { + "type": "number", + "description": "The longitude of the point." + } + }, + "required": ["latitude", "longitude"] +}; + +const PlaceIdSchema = { + "type": "string", + "description": "The Place ID of the point." +}; + +const AddressSchema = { + "type": "string", + "description": "The address of the point." +}; +export const GoogleMapsPlatformComputeRoutes: Tool = { + name: 'GoogleMapsPlatformComputeRoutes', + description: ` + **Tool Name:** Route Computation Tool + **Core Functionality:** Computes a travel route between a specified origin and destination. + **Supported Travel Modes:** DRIVE (default), WALK. + + **Input Requirements (CRITICAL):** + Requires both **origin** and **destination**. Each must be provided using one of the following methods, nested within its respective field: + * **address:** (string, e.g., "Eiffel Tower, Paris"). Note: The more granular or specific the input address is, the better the results will be. + * **lat_lng:** (object, {"latitude": number, "longitude": number}) + * **place_id:** (string, e.g., "ChIJOwE_Id1w5EAR4Q27FkL6T_0") Note: This id can be obtained from Google Maps Places API or from GoogleMapsPlatformPlacesSearchText. + + Any combination of input types is allowed (e.g., origin by address, destination by lat_lng). If either the origin or destination is missing, **you MUST ask the user for clarification** before attempting to call the tool. + + **Example Tool Call:** + {"origin":{"address":"Eiffel Tower"},"destination":{"place_id":"ChIJt_5xIthw5EARoJ71mGq7t74"},"travel_mode":"DRIVE"} + `, + inputSchema: { + "type": "object", + "description": "Schema for computing routes between an origin and a destination.", + "properties": { + "origin": { + "type": "object", + "description": "The starting point for the route (e.g., 'Eiffel Tower, Paris').", + "oneOf": [ + { "properties": { "lat_lng": LatLngSchema }, "required": ["lat_lng"] }, + { "properties": { "place_id": PlaceIdSchema }, "required": ["place_id"] }, + { "properties": { "address": AddressSchema }, "required": ["address"] } + ] + }, + "destination": { + "type": "object", + "description": "The ending point for the route (e.g., 'Louvre Museum, Paris').", + "oneOf": [ + { "properties": { "lat_lng": LatLngSchema }, "required": ["lat_lng"] }, + { "properties": { "place_id": PlaceIdSchema }, "required": ["place_id"] }, + { "properties": { "address": AddressSchema }, "required": ["address"] } + ] + }, + "travel_mode": { + "type": "string", + "description": "The mode of travel (e.g., 'DRIVE', 'WALK').", + "enum": ["DRIVE", "WALK"], + "default": "DRIVE" + } + }, + "required": ["origin", "destination"], + "additionalProperties": false + }, +}; + +export async function handleGoogleMapsPlatformComputeRoutes(request: any, server: Server) { + try { + const origin = request.params.arguments?.origin; + const destination = request.params.arguments?.destination; + let travelMode: string = request.params.arguments?.travelMode as string || "DRIVE"; + + server.sendLoggingMessage({ + level: "info", + data: `Calling tool GoogleMapsPlatformComputeRoutes with: { origin: ${JSON.stringify(getWaypoint(origin))}, destination: ${JSON.stringify(getWaypoint(destination))}, travelMode: ${travelMode} }`, + }); + + try { + const apiKey = getGoogleMapsApiKey(); + const url = `${GoogleMapsPlatformServiceUrl}/routes:compute?key=${apiKey}`; + const params: any = { + origin: getWaypoint(origin), + destination: getWaypoint(destination), + travel_mode: travelMode + }; + + const headers = { + 'Content-Type': 'application/json' + }; + + const googleMapsPlatformServiceResponse = await axios.post( + url, + params, + { + headers + } + ); + + let mcpResponse = { + "response": { + "contexts": googleMapsPlatformServiceResponse.data + }, + "status": googleMapsPlatformServiceResponse.status.toString(), + }; + + return { + content: [{ + type: 'text', + text: JSON.stringify(mcpResponse) + }] + }; + + } catch (error: any) { + let errorMessage = ""; + if (error.response && error.response.data && error.response.data.error && error.response.data.error.message) { + errorMessage = error.response.data.error.message; + } + + + server.sendLoggingMessage({ + level: "error", + data: `Error executing tool ${request.params.name}: ${error} \nErrorMessage: ${errorMessage}`, + }); + + return { + content: [{ type: 'text', text: errorMessage }] + }; + } + + } catch (error) { + server.sendLoggingMessage({ + level: "error", + data: `Error executing tool ${request.params.name}: ${error}`, + }); + return { + content: [{ type: 'text', text: JSON.stringify(error) }] + }; + } +} + +function getWaypoint(waypoint: any) { + if (waypoint.lat_lng) { + return { latLng: waypoint.lat_lng }; + } else if (waypoint.place_id) { + return { placeId: waypoint.place_id }; + } else if (waypoint.address) { + return { address: waypoint.address }; + } + return {}; +} diff --git a/packages/maps-grounding-essentials/tests/integration.test.ts b/packages/maps-grounding-essentials/tests/integration.test.ts new file mode 100644 index 0000000..964330d --- /dev/null +++ b/packages/maps-grounding-essentials/tests/integration.test.ts @@ -0,0 +1,157 @@ +/** + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { expect, test, describe, spyOn } from "bun:test"; +import { getServer } from "../index.js"; +import { handleGoogleMapsPlatformPlacesSearchText } from "../places-search-text.js"; +import { handleGoogleMapsPlatformWeatherLookup } from "../weather-lookup.js"; // New import +import { handleGoogleMapsPlatformComputeRoutes } from "../routes-compute.js"; // New import +import { CallToolRequest } from "@modelcontextprotocol/sdk/types.js"; + +const server = getServer(); +spyOn(server, "sendLoggingMessage").mockImplementation(async () => {}); + +describe("Google Maps Platform Maps Grounding Essentials MCP Server - Integration", () => { + test( + "GoogleMapsPlatformPlacesSearchText tool returns valid response", + async () => { + // Ensure GOOGLE_MAPS_API_KEY is set in the environment for this test to pass. + // For example: export GOOGLE_MAPS_API_KEY="YOUR_API_KEY" + if (!process.env.GOOGLE_MAPS_API_KEY) { + throw new Error("GOOGLE_MAPS_API_KEY environment variable is not set. Please set it to run this integration test."); + } + + const request = { + method: "tools/call" as const, + params: { + name: "GoogleMapsPlatformPlacesSearchText", + arguments: { + text_query: "restaurants in New York", + }, + }, + }; + + const result = await handleGoogleMapsPlatformPlacesSearchText(request as CallToolRequest, server); + + expect(result.content).toBeDefined(); + expect(result.content).toBeArray(); + expect(result.content!.length).toBeGreaterThan(0); + + const content = JSON.parse(result.content![0].text!); + + expect(content.response).toBeDefined(); + expect(content.response.contexts).toBeDefined(); + expect(content.response.contexts.places).toBeDefined(); + expect(content.response.contexts.places).toBeArray(); + expect(content.response.contexts.places.length).toBeGreaterThan(0); + expect(content.response.contexts.places[0].place).toBeDefined(); + expect(content.response.contexts.places[0].id).toBeDefined(); + expect(content.response.contexts.places[0].location).toBeDefined(); + expect(content.response.contexts.places[0].googleMapsLinks).toBeDefined(); + expect(content.response.contexts.summary).toBeDefined(); + expect(typeof content.response.contexts.summary).toBe('string'); + expect(content.status).toBe("200"); + }, + 60000 + ); + + test( + "GoogleMapsPlatformWeatherLookup tool returns valid response", + async () => { + // Ensure GOOGLE_MAPS_API_KEY is set in the environment for this test to pass. + if (!process.env.GOOGLE_MAPS_API_KEY) { + throw new Error("GOOGLE_MAPS_API_KEY environment variable is not set. Please set it to run this integration test."); + } + + const request = { + method: "tools/call" as const, + params: { + name: "GoogleMapsPlatformWeatherLookup", + arguments: { + address: "New York, NY" + }, + }, + }; + + const result = await handleGoogleMapsPlatformWeatherLookup(request as CallToolRequest, server); + + expect(result.content).toBeDefined(); + expect(result.content).toBeArray(); + expect(result.content!.length).toBeGreaterThan(0); + + const content = JSON.parse(result.content![0].text!); + + expect(content.response).toBeDefined(); + expect(content.response.contexts).toBeDefined(); + expect(content.response.contexts.temperature).toBeDefined(); + expect(content.response.contexts.feelsLikeTemperature).toBeDefined(); + expect(content.response.contexts.heatIndex).toBeDefined(); + expect(content.response.contexts.airPressure).toBeDefined(); + expect(content.response.contexts.weatherCondition).toBeDefined(); + expect(content.response.contexts.precipitation).toBeDefined(); + expect(content.response.contexts.wind).toBeDefined(); + expect(content.response.contexts.relativeHumidity).toBeDefined(); + expect(content.response.contexts.uvIndex).toBeDefined(); + expect(content.response.contexts.thunderstormProbability).toBeDefined(); + expect(content.response.contexts.cloudCover).toBeDefined(); + expect(content.response.contexts.geocodedAddress).toBeDefined(); + expect(content.status).toBe("200"); + }, + 60000 + ); + + test( + "GoogleMapsPlatformComputeRoutes tool returns valid response", + async () => { + // Ensure GOOGLE_MAPS_API_KEY is set in the environment for this test to pass. + if (!process.env.GOOGLE_MAPS_API_KEY) { + throw new Error("GOOGLE_MAPS_API_KEY environment variable is not set. Please set it to run this integration test."); + } + + const request = { + method: "tools/call" as const, + params: { + name: "GoogleMapsPlatformComputeRoutes", + arguments: { + origin: { address: "Eiffel Tower, Paris" }, + destination: { address: "Louvre Museum, Paris" }, + travel_mode: "WALK", + }, + }, + }; + + const result = await handleGoogleMapsPlatformComputeRoutes(request as CallToolRequest, server); + + expect(result.content).toBeDefined(); + expect(result.content).toBeArray(); + expect(result.content!.length).toBeGreaterThan(0); + + + + const content = JSON.parse(result.content![0].text!); + + expect(content.response).toBeDefined(); + expect(content.response.contexts).toBeDefined(); + expect(content.response.contexts.routes).toBeDefined(); + expect(content.response.contexts.routes).toBeArray(); + expect(content.response.contexts.routes.length).toBeGreaterThan(0); + expect(content.response.contexts.routes[0].distanceMeters).toBeDefined(); + expect(content.response.contexts.routes[0].duration).toBeDefined(); + expect(content.status).toBe("200"); + }, + 60000 + ); +}); diff --git a/packages/maps-grounding-essentials/tsconfig.json b/packages/maps-grounding-essentials/tsconfig.json new file mode 100644 index 0000000..74c5877 --- /dev/null +++ b/packages/maps-grounding-essentials/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "resolveJsonModule": true, + "outDir": "./dist", + "rootDir": "." + }, + "include": [ + "./**/*.ts" + ], + "exclude": [ + "node_modules" + ] +} \ No newline at end of file diff --git a/packages/maps-grounding-essentials/weather-lookup.ts b/packages/maps-grounding-essentials/weather-lookup.ts new file mode 100644 index 0000000..7a366f1 --- /dev/null +++ b/packages/maps-grounding-essentials/weather-lookup.ts @@ -0,0 +1,166 @@ +/** + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Tool } from '@modelcontextprotocol/sdk/types.js'; +import { GoogleMapsPlatformServiceUrl, getGoogleMapsApiKey } from './config.js'; +import axios from 'axios'; +import { Server } from '@modelcontextprotocol/sdk/server/index.js'; + +interface Date { + year?: number; + month?: number; + day?: number; +} + +export const GoogleMapsPlatformWeatherLookup: Tool = { + name: 'GoogleMapsPlatformWeatherLookup', + description: ` + **Tool Name:** Weather Information Tool (Google Maps Platform) + **Core Functionality:** Provides current conditions, hourly, and daily forecasts for any location. Use this tool for all weather-related inquiries. + **Specific Data Available:** Temperature (Current, Feels Like, Max/Min, Heat Index), Wind (Speed, Gusts, Direction), Celestial Events (Sunrise/Sunset, Moon Phase), Precipitation (Type, Probability, Quantity/QPF), Atmospheric Conditions (UV Index, Humidity, Cloud Cover, Thunderstorm Probability), and Geocoded Location Address. + + **Input Requirements (CRITICAL):** + * **Current Conditions:** Requires only a location (e.g., city or address). + * **Hourly Forecasts:** Requires a location and an **hour** (0-23). Use if the user asks for weather at a specific time or using terms like "next few hours," or "later today." + * **Daily Forecasts:** Requires a location and a full date. + + Date Handling (CRITICAL): User-provided dates and hours MUST be provided in the local timezone of the requested location. Dates MUST be broken down into separate integer parameters: year, month, and day. The required format for these parameters is: {"year": , "month": , "day": }. + `, + inputSchema: { + "type": "object", + "description": "Schema for requesting weather conditions based on a specific location, date, and hour, " + + "with optional unit system preferences.", + "properties": { + "address": { + "type": "string", + "description": "The address of the location to get the weather conditions for. " + + "This can be a street address, city, zip code, etc." + }, + "date": { + "type": "object", + "description": "The date of the required weather information", + "properties": { + "year": { + "type": "integer", + "description": "The year of the requested weather information." + }, + "month": { + "type": "integer", + "description": "The month of the requested weather information." + }, + "day": { + "type": "integer", + "description": "The day of the requested weather information." + } + } + }, + "hour": { + "type": "integer", + "description": "The hour of the requested weather information, in 24-hour format (0-23). ", + "minimum": 0, + "maximum": 23 + }, + "unitsSystem": { + "type": "string", + "description": "The units system to use for the returned weather conditions.", + "enum": [ + "METRIC", + "IMPERIAL" + ], + "default": "METRIC" + } + }, + "required": ["address"], + "additionalProperties": false + }, +}; + +export async function handleGoogleMapsPlatformWeatherLookup(request: any, server: Server) { + try { + let address: string = request.params.arguments?.address as string; + let date: Date | undefined = request.params.arguments?.date as Date | {}; + let hour: number | undefined = request.params.arguments?.hour as number | undefined; + let unitsSystem: "METRIC" | "IMPERIAL" | undefined = request.params.arguments?.unitsSystem as "METRIC" | "IMPERIAL" | undefined; + + // Log user request for debugging purposes + server.sendLoggingMessage({ + level: "info", + data: `Calling tool GoogleMapsPlatformWeatherLookup with address: ${address}, + date: {year: ${date?.year}, month: ${date?.month}, day: ${date?.day}}, + hour: ${hour}, unitsSystem: ${unitsSystem}`, + }); + + try { + const apiKey = getGoogleMapsApiKey(); + const url = `${GoogleMapsPlatformServiceUrl}/weather:lookup?key=${apiKey}`; + const params: any = { address }; + if (date) params.date = date; + if (hour !== undefined) params.hour = hour; + if (unitsSystem) params.unitsSystem = unitsSystem; + + const headers = { + 'Content-Type': 'application/json' + }; + + const googleMapsPlatformServiceResponse = await axios.post( + url, + params, + { + headers + } + ); + + let mcpResponse = { + "response": { + "contexts": googleMapsPlatformServiceResponse.data + }, + "status": googleMapsPlatformServiceResponse.status.toString(), + }; + + return { + content: [{ + type: 'text', + text: JSON.stringify(mcpResponse) + }] + }; + + } catch (error: any) { + // Log the error for debugging purposes + let errorMessage = ""; + if (error.response && error.response.data && error.response.data.error && error.response.data.error.message) { + errorMessage = error.response.data.error.message; + } + + server.sendLoggingMessage({ + level: "error", + data: `Error executing tool ${request.params.name}: ${error} \nErrorMessage: ${errorMessage}`, + }); + + return { + content: [{ type: 'text', text: errorMessage }] + }; + } + + } catch (error) { + server.sendLoggingMessage({ + level: "error", + data: `Error executing tool ${request.params.name}: ${error}`, + }); + return { + content: [{ type: 'text', text: JSON.stringify(error) }] + }; + } +}