MCP Integration Guide: Step-by-Step for Claude, ChatGPT, and Custom Agents
This guide provides detailed instructions for integrating BuyWhere's Model Context Protocol (MCP) server with various AI agent platforms.
Overview
BuyWhere's MCP server exposes product catalog functionality as discoverable tools that AI agents can call directly. This eliminates the need for agents to understand REST API endpoints and instead lets them interact with BuyWhere as a natural shopping tool.
Table of Contents
- Prerequisites
- Claude Desktop Integration
- ChatGPT Plugin Integration
- Custom Agent Integration (Python/JS)
- Troubleshooting
- Testing Your Integration
Prerequisites
Before beginning any integration, ensure you have:
- A BuyWhere API key (obtainable at https://buywhere.ai/api)
- The BuyWhere MCP server source code (available in this repository)
- Python 3.10+ installed
- Basic familiarity with your target agent platform
Install Dependencies
# Clone the repository if you haven't already
git clone https://github.com/buywhere/buywhere-api.git
cd buywhere-api
# Create virtual environment
python3 -m venv venv
source venv/bin/activate # Linux/macOS
# venv\Scripts\activate # Windows
# Install dependencies
pip install -r requirements.txt
Claude Desktop Integration
Claude Desktop supports MCP servers natively through configuration.
Step 1: Configure Claude Desktop
Locate your Claude Desktop configuration file:
- macOS:
~/Library/Application Support/Claude/claude_desktop_config.json - Linux:
~/.config/Claude/claude_desktop_config.json - Windows:
%APPDATA%\Claude\claude_desktop_config.json
Add the BuyWhere MCP server configuration:
{
"mcpServers": {
"buywhere": {
"command": "python",
"args": [
"/absolute/path/to/buywhere-api/mcp_server.py"
],
"env": {
"BUYWHERE_API_KEY": "your_buywhere_api_key_here",
"BUYWHERE_API_URL": "https://api.buywhere.ai"
}
}
}
}
Important: Use absolute paths to mcp_server.py. Relative paths will not work.
Step 2: Restart Claude Desktop
Completely close Claude Desktop and reopen it to load the new configuration.
Step 3: Verify Connection
Ask Claude Desktop:
What tools do you have available from BuyWhere?
You should see a response listing the available tools:
search_productsget_productcompare_productsget_dealslist_categories
Step 4: Start Using BuyWhere Tools
You can now naturally ask Claude to:
- "Search for wireless headphones under SGD 100 on BuyWhere"
- "Compare prices for iPhone 15 Pro across Singapore retailers"
- "Find me the best deal on Nintendo Switch OLED"
- "Show me trending products in the electronics category"
ChatGPT Plugin Integration
While ChatGPT doesn't natively support MCP, you can create a custom plugin that bridges ChatGPT to the BuyWhere MCP server.
Step 1: Create the Plugin Manifest
Create an ai-plugin.json file for your ChatGPT plugin:
{
"schema_version": "v1",
"name_for_human": "BuyWhere Shopping",
"name_for_model": "buywhere",
"description_for_human": "Search Singapore e-commerce platforms for products, compare prices, and find the best deals.",
"description_for_model": "Use this tool to search for products, compare prices across retailers, and find deals in Singapore e-commerce. The user will specify what they want to buy, and you'll help them find it using BuyWhere's product catalog.",
"auth": {
"type": "none"
},
"api": {
"type": "openapi",
"url": "https://your-domain.com/openapi.json"
},
"logo": "https://your-domain.com/logo.png",
"contact_email": "support@your-domain.com",
"legal_info_url": "https://your-domain.com/legal"
}
Step 2: Implement the MCP Bridge
Create a simple API server that translates ChatGPT plugin calls to MCP tool calls:
# buywhere_chatgpt_plugin.py
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import subprocess
import json
import os
app = FastAPI(title="BuyWhere ChatGPT Plugin MCP Bridge")
class SearchRequest(BaseModel):
query: str
limit: int = 10
class PriceComparisonRequest(BaseModel):
product_name: str
limit: int = 5
@app.post("/search")
async def search_products(request: SearchRequest):
# Call MCP search tool via subprocess
mcp_request = {
"jsonrpc": "2.0",
"method": "tools/call",
"params": {
"name": "search_products",
"arguments": {
"query": request.query,
"limit": request.limit
}
},
"id": 1
}
# In a real implementation, you'd use proper MCP client library
# This is a simplified example using subprocess
env = os.environ.copy()
env["BUYWHERE_API_KEY"] = "your_api_key_here"
env["BUYWHERE_API_URL"] = "https://api.buywhere.ai"
# This would normally use an MCP client - simplified for example
return {"results": []} # Replace with actual implementation
# Similar endpoints for price comparison, etc.
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
Step 3: Host Your Plugin
Deploy your plugin bridge to a publicly accessible HTTPS endpoint (required by ChatGPT).
Step 4: Install in ChatGPT
- In ChatGPT, go to Settings → Beta features → Enable "Plugins"
- Go to Plugin Store → Develop your own plugin
- Enter your plugin's manifest URL
- Complete the installation process
Step 5: Use BuyWhere in ChatGPT
Once installed, you can ask ChatGPT:
Help me find the best price for AirPods Pro in Singapore
The plugin will use your MCP bridge to call BuyWhere's tools.
Custom Agent Integration (Python/JS)
For custom agents, you can integrate directly with the BuyWhere MCP server using MCP client libraries.
Python Integration
Step 1: Install MCP Client Library
pip install mcp
Step 2: Create MCP Client Connection
# buywhere_mcp_client.py
import asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def main():
# Configure server parameters
server_params = StdioServerParameters(
command="python",
args=["/absolute/path/to/buywhere-api/mcp_server.py"],
env={
"BUYWHERE_API_KEY": "your_api_key_here",
"BUYWHERE_API_URL": "https://api.buywhere.ai"
}
)
# Connect to server
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
# Initialize connection
await session.initialize()
# List available tools
tools = await session.list_tools()
print("Available tools:", [tool.name for tool in tools.tools])
# Call a tool - search for products
result = await session.call_tool(
"search_products",
arguments={
"query": "wireless headphones",
"limit": 5
}
)
print("Search results:", result.content)
# Call another tool - compare prices
price_result = await session.call_tool(
"compare_prices",
arguments={
"product_name": "iPhone 15 Pro",
"limit": 3
}
)
print("Price comparison:", price_result.content)
if __name__ == "__main__":
asyncio.run(main())
JavaScript/TypeScript Integration
Step 1: Install MCP Client
npm install @modelcontextprotocol/sdk
Step 2: Create MCP Client Connection
// buywhere-mcp-client.js
import { Client } from '@modelcontextprotocol/sdk';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/stdio.js';
async function main() {
// Create client
const client = new Client({
name: "buywhere-custom-agent",
version: "1.0.0"
});
// Configure transport
const transport = new StdioClientTransport({
command: "python",
args: ["/absolute/path/to/buywhere-api/mcp_server.py"],
env: {
BUYWHERE_API_KEY: "your_api_key_here",
BUYWHERE_API_URL: "https://api.buywhere.ai"
}
});
// Connect
await client.connect(transport);
// Initialize
await client.initialize();
// List tools
const tools = await client.listTools();
console.log("Available tools:", tools.tools.map(t => t.name));
// Call search tool
const searchResult = await client.callTool("search_products", {
query: "wireless headphones",
limit: 5
});
console.log("Search results:", searchResult.content);
// Call price comparison tool
const priceResult = await client.callTool("compare_prices", {
product_name: "iPhone 15 Pro",
limit: 3
});
console.log("Price comparison:", priceResult.content);
// Clean up
await client.close();
}
main().catch(console.error);
Direct API Alternative
If MCP integration isn't feasible for your use case, you can still use BuyWhere's REST API directly:
import requests
API_KEY = "your_api_key_here"
BASE_URL = "https://api.buywhere.ai/v2"
headers = {"Authorization": f"Bearer {API_KEY}"}
# Search products
response = requests.get(
f"{BASE_URL}/products",
headers=headers,
params={"q": "laptop", "limit": 10, "sort_by": "price_asc"}
)
products = response.json()
for product in products["items"]:
print(f"{product['name']} - SGD {product['price']} ({product['source']})")
print(f" Confidence: {product['confidence_score']}")
Troubleshooting
Common Issues
1. "Server not found" or connection errors
- Verify you're using absolute paths to
mcp_server.py - Check that the MCP server process is running
- Ensure your firewall allows connections if using HTTP transport
2. Authentication errors (401/403)
- Confirm your BuyWhere API key is valid and active
- Check that the API key has required scopes
- Verify you haven't exceeded rate limits
3. Tool not found errors
- Ensure the MCP server is properly initialized
- Verify you're calling the correct tool names (check available tools first)
- Make sure you're using the latest version of the MCP server
4. Timeout or hanging connections
- Check network connectivity to
api.buywhere.ai - Verify your API key permissions
- Consider using HTTP transport instead of STDIO for long-running agents
Debugging Tips
- Check MCP Server Logs: Run the MCP server with verbose logging to see incoming requests
- Verify Environment Variables: Ensure
BUYWHERE_API_KEYandBUYWHERE_API_URLare correctly set - Test MCP Server Directly: Use the health check endpoint or STDIO test from the deployment guide
- Use MCP Inspector: For debugging MCP connections, consider using MCP inspector tools
Testing Your Integration
Test Cases to Verify
- Tool Discovery: Confirm your agent can list all available BuyWhere tools
- Basic Search: Search for a common product and verify results
- Price Comparison: Compare prices for a specific product across retailers
- Batch Lookup: Look up multiple products by ID (if applicable to your agent)
- Error Handling: Test how your agent handles invalid queries or API errors
Sample Test Script
# test_buywhere_integration.py
import asyncio
from buywhere_mcp_client import buywhere_mcp_client # Import your client implementation
async def run_tests():
client = await buywhere_mcp_client()
# Test 1: List tools
tools = await client.list_tools()
assert len(tools) > 0, "Should have available tools"
print(f"✓ Found {len(tools)} tools")
# Test 2: Search products
search_results = await client.call_tool("search_products", {
"query": "bluetooth speaker",
"limit": 3
})
assert len(search_results) > 0, "Should return search results"
print("✓ Search test passed")
# Test 3: Price comparison
price_results = await client.call_tool("compare_prices", {
"product_name": "Samsung Galaxy S23",
"limit": 3
})
assert len(price_results) > 0, "Should return price comparison"
print("✓ Price comparison test passed")
# Test 4: Browse categories
categories = await client.call_tool("browse_categories", {})
assert len(categories) > 0, "Should return categories"
print("✓ Category browsing test passed")
await client.close()
print("\n🎉 All tests passed!")
if __name__ == "__main__":
asyncio.run(run_tests())
Best Practices
- Secure API Keys: Never hard-code API keys in client applications. Use environment variables or secure secret management.
- Handle Errors Gracefully: Implement proper error handling for MCP connection failures and API errors.
- Rate Limiting: Respect BuyWhere's rate limits (1000 requests/minute by default) and implement retry logic with exponential backoff.
- Cache When Appropriate: Consider caching frequent queries or product details to reduce API calls.
- Keep MCP Server Updated: Regularly pull updates to the BuyWhere MCP server to get new tools and improvements.
- Monitor Usage: Track your agent's usage patterns to optimize costs and performance.
Next Steps
- Explore Advanced Tools: Try out all seven MCP tools (
search,price_comparison,batch_lookup,bulk_compare,explore,best_price,compare_matrix) - Build Custom Workflows: Combine multiple tools to create sophisticated shopping workflows for your agent
- Contribute: If you improve the integration or add features, consider contributing back to the BuyWhere MCP repository
- Stay Updated: Check the BuyWhere documentation for new features and best practices
Support
If you encounter issues or have questions:
- Documentation: https://docs.buywhere.ai
- API Reference: https://api.buywhere.ai/docs
- GitHub Issues: https://github.com/buywhere/buywhere-api/issues
- Email Support: support@buywhere.ai
Happy building! 🚀