Kroger MCP Server
Allows Large Language Models to interact with Kroger's grocery services, enabling product search, store lookup, and cart management through the Model Context Protocol.
README
Kroger MCP Server
This project implements a Model Context Protocol (MCP) server that wraps the Kroger API. It allows Large Language Models (LLMs) like Anthropic's Claude to interact with Kroger's grocery services, enabling features such as product search, store lookup, and cart management.
Features
- OAuth2 Authentication: Handles client credentials for general data and user-based authorization for cart operations.
- Product Search: Search for products by keyword at specific store locations.
- Product Details: Retrieve detailed product information including price, availability, and fulfillment options.
- Store Locations: Find Kroger store locations by ZIP code.
- Cart Management: Add items to a user's Kroger shopping cart (requires user authorization).
1. Configuration
Before running the server, you need to configure your Kroger API credentials and OAuth2 settings.
1.1. API Credentials (Client ID & Secret)
- Obtain Credentials: Register an application on the Kroger Developer Portal to get a
Client IDandClient Secret. - Set Credentials: You can set these credentials in one of two ways:
config.py(Recommended for simplicity for local use): Open theconfig.pyfile and replace the placeholder values forKROGER_CLIENT_IDandKROGER_CLIENT_SECRETwith your actual credentials.# config.py KROGER_CLIENT_ID = "YOUR_ACTUAL_CLIENT_ID" KROGER_CLIENT_SECRET = "YOUR_ACTUAL_CLIENT_SECRET"- Environment Variables: The
auth.pyscript can be modified to also reados.environ.get("KROGER_CLIENT_ID")andos.environ.get("KROGER_CLIENT_SECRET")if you prefer managing secrets via environment variables. (Note: Current implementation intools.pyandserver.pydirectly usesconfig.pyvalues).
1.2. User Authorization (for Cart Operations)
To use tools that modify a user's cart (e.g., add_to_cart), the user must authorize the application. This server uses the OAuth2 Authorization Code Grant flow.
-
Redirect URI: Ensure the
KROGER_REDIRECT_URIinconfig.pymatches the Redirect URI registered with your Kroger application. For local testing,http://localhost:8080/callbackis a common default, but you'll need a way to capture the code from this redirect.# config.py KROGER_REDIRECT_URI = "http://localhost:8080/callback" # Or your configured URI -
Obtaining an Authorization Code & Refresh Token:
- Run the
auth.pyscript directly (python auth.py). - It will print an "Authorization URL". Copy and paste this URL into your web browser.
- Log in with your Kroger account and grant access.
- You will be redirected to your
KROGER_REDIRECT_URI. The URL in your browser's address bar will now contain an authorizationcode(e.g.,http://localhost:8080/callback?code=YOUR_AUTH_CODE&...). - Copy this
code. - Paste the
codeback into theauth.pyscript when prompted. - The script will then exchange the code for an access token and a refresh token.
- Crucially, securely store the displayed
refresh_token.
- Run the
-
Configuring the Refresh Token:
- To enable cart operations across server restarts without re-authenticating each time, you should set the obtained
refresh_tokeninconfig.pyor as an environment variable thatAuthManagercan load. - Modify
AuthManager.__init__inauth.pyto load thisKROGER_USER_REFRESH_TOKENfromconfig.pyor environment:And then add# In auth.py -> AuthManager.__init__ # self.user_refresh_token = os.environ.get("KROGER_USER_REFRESH_TOKEN") # OR # from config import KROGER_USER_REFRESH_TOKEN # Add this to config.py # self.user_refresh_token = KROGER_USER_REFRESH_TOKENKROGER_USER_REFRESH_TOKEN = "YOUR_SAVED_REFRESH_TOKEN"toconfig.py. - When
get_user_token()is called, if an access token is expired or missing, it will attempt to use this refresh token.
- To enable cart operations across server restarts without re-authenticating each time, you should set the obtained
2. Running the Server
- Install Dependencies: If you haven't already, install the required Python libraries:
(Note: Thepip install requests mcpmcplibrary name is assumed; adjust if it's different, e.g.,modelcontextprotocol). - Start the Server:
Run the
server.pyscript from your terminal:python server.py - Server Operation:
- The server uses STDIO (standard input/output) for communication with the MCP client. It does not open any network ports.
- Upon starting, it will print initialization messages, including a list of registered tools.
- It will then listen for JSON-RPC requests from the MCP client.
- Stopping the Server:
Press
Ctrl+Cin the terminal where the server is running.
3. MCP Client Integration
3.1. Claude Desktop
- Go to
Settingsin Claude Desktop. - Navigate to
Integrations(or a similar section for MCP servers). - Click
Add MCP Server(or equivalent). - Provide the command to run the server. This usually involves specifying the Python interpreter and the path to
server.py. For example:- If Python is in your PATH:
python /path/to/your/project/server.py - Otherwise:
/path/to/your/python /path/to/your/project/server.py
- If Python is in your PATH:
- Once added, Claude will be able to see and invoke the Kroger tools (e.g.,
find_stores,search_products).
3.2. Programmatic Use (Example)
Developers can also interact with the server programmatically using an MCP client library.
# This is a conceptual example based on the MCP specification.
# The actual library might differ.
from modelcontext import Client, StdioClientTransport # Assuming library structure
async def main():
client = Client(name="example-kroger-client", version="1.0", capabilities={})
# Adjust command if python/server.py are not in PATH or need full paths
python_executable = "python" # Or full path to python interpreter
server_script_path = "server.py" # Or full path to server.py
transport = StdioClientTransport(command=[python_executable, server_script_path])
await client.connect(transport)
# Example: Find stores
try:
store_results = await client.call_tool(
"find_stores",
{"zip_code": "45202", "limit": 1}
)
print("Store Search Results:", store_results)
if store_results and not store_results.get("error") and len(store_results) > 0:
location_id = store_results[0].get("locationId")
if location_id:
# Example: Search products
product_results = await client.call_tool(
"search_products",
{"query": "milk", "location_id": location_id, "limit": 2}
)
print("Product Search Results:", product_results)
# Example: Add to cart (requires user auth token to be set up in server)
# Ensure product_results[0] exists and has 'productId'
if product_results and not product_results.get("error") and len(product_results) > 0:
product_id = product_results[0].get("productId")
cart_result = await client.call_tool(
"add_to_cart",
{"product_id": product_id, "quantity": 1, "location_id": location_id}
)
print("Add to Cart Result:", cart_result)
except Exception as e:
print(f"An error occurred: {e}")
finally:
await client.disconnect()
if __name__ == "__main__":
# For asyncio if your client library uses it
# import asyncio
# asyncio.run(main())
print("Run the async main() function with an asyncio event loop if needed by your MCP client library.")
4. Example Dialogue with LLM
User: "I need two gallons of organic whole milk and a dozen eggs from a Kroger near 90210."
LLM (Assistant) Internal Steps:
- (Optional: LLM asks for user's ZIP code if not provided or ambiguous)
- LLM calls
find_stores:{"zip_code": "90210", "limit": 1}- Server returns store details, e.g.,
[{ "locationId": "01400123", "name": "Beverly Hills Kroger", ... }]
- Server returns store details, e.g.,
- LLM calls
search_products(for milk):{"query": "organic whole milk", "location_id": "01400123", "limit": 5}- Server returns list of milk products. LLM selects one, e.g.,
{"productId": "0001111060404", "description": "Simple Truth Organic Milk...", ...}.
- Server returns list of milk products. LLM selects one, e.g.,
- LLM calls
search_products(for eggs):{"query": "dozen eggs", "location_id": "01400123", "limit": 3}- Server returns list of egg products. LLM selects one.
- (User authorization for cart must be completed if not done already)
- LLM calls
add_to_cart(for milk):{"product_id": "0001111060404", "quantity": 2, "location_id": "01400123"}- Server confirms addition.
- LLM calls
add_to_cart(for eggs):{"product_id": "...", "quantity": 1, "location_id": "01400123"}- Server confirms addition.
LLM (Assistant) to User: "Okay, I've found the Beverly Hills Kroger. I've added 2 gallons of Simple Truth Organic Whole Milk and one dozen eggs to your cart. Anything else?"
5. Error Scenarios
- Missing User Authorization: If you attempt to use
add_to_cartwithout the user having authorized the application, the tool will return an error:The LLM should guide the user to perform the authorization step (see Section 1.2). The authorization URL might be included in the error message.{ "error": "User authentication required.", "message": "No user access token found. The user needs to authorize the application...", "action_needed": "User must complete OAuth2 authorization flow." } - Invalid/Expired Tokens: If an access token is expired, the
AuthManagerwill attempt to refresh it. If the refresh token is also invalid (e.g., for user tokens after a 401 error onadd_to_cart), re-authorization will be required. - API Rate Limits: Kroger's API has rate limits (e.g., see developer.kroger.com/support/rate-limits/). If the server hits these limits, API calls will fail. The server will return an error from Kroger, typically with an HTTP 429 status code. The LLM should inform the user to try again later.
- Other API Errors: If Kroger's API returns other errors (e.g., invalid product ID, store not found for locationId), the tools will return a JSON dictionary containing
error,details,status_code(the HTTP status from Kroger), and possiblyraw_responseorkroger_errorfields.
6. Available Tools
The server exposes the following tools to the LLM:
find_stores(zip_code: str, radius_miles: int = 10, limit: int = 5) -> list | dict- Description: Find Kroger store locations by ZIP code (returns nearest stores with IDs).
search_products(query: str, location_id: str, limit: int = 10) -> list | dict- Description: Search Kroger products by keyword at a given store.
get_product(product_id: str, location_id: str) -> dict- Description: Get detailed information for a product by ID (price, size, stock, fulfillment options).
add_to_cart(product_id: str, quantity: int, location_id: str) -> dict- Description: Add a product to the user's Kroger cart (requires user authentication).
(The descriptions above are based on the @tool decorators in tools.py.)
推荐服务器
Baidu Map
百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Playwright MCP Server
一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。
Magic Component Platform (MCP)
一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。
Audiense Insights MCP Server
通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。
VeyraX
一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。
graphlit-mcp-server
模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。
Kagi MCP Server
一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。
e2b-mcp-server
使用 MCP 通过 e2b 运行代码。
Neon MCP Server
用于与 Neon 管理 API 和数据库交互的 MCP 服务器
Exa MCP Server
模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。