MCP Integration Guide
MCP Integration Guide
Section titled “MCP Integration Guide”Model Context Protocol (MCP) enables the agent to execute external tools. This is optional - the agent works without it.
What is MCP?
Section titled “What is MCP?”MCP provides tool execution via JSON-RPC 2.0:
- External tools: Search products, get purchase history, fetch web pages
- Server-side execution: Tools run on MCP server, not locally
- Authentication: Requires auth token from AWS Secrets Manager
When enabled, the agent can call 6 tools for shopping assistance.
Setup Checklist
Section titled “Setup Checklist”Prerequisites
Section titled “Prerequisites”- AWS CLI configured with SSO access
- Access to
rover-mcp/auth-tokensin AWS Secrets Manager - MCP server URL (stage or prod)
Configuration Steps
Section titled “Configuration Steps”- Get auth token from AWS:
# Login to AWS SSOaws sso login --profile stage-services-admin
# Retrieve tokenaws secretsmanager get-secret-value \ --secret-id rover-mcp/auth-tokens \ --profile stage-services-admin \ --query SecretString \ --output text- Add token to
.env:
# Copy example file if neededcp .env.example .env
# Edit .env and add:ROVER_MCP_AUTHORIZATION=your-token-from-aws- Verify MCP config in
settings.yaml:
rover_mcp: server_url: https://stage-partners-gateway.fetchrewards.com/rover-mcp timeout: 90.0- Test connection:
# Direct server testcurl -H "Authorization: Bearer $ROVER_MCP_AUTHORIZATION" \ https://stage-partners-gateway.fetchrewards.com/rover-mcp/healthExpected response: {"status": "ok"}
Available Tools
Section titled “Available Tools”The agent has access to 6 MCP tools:
1. search_products
Section titled “1. search_products”Search for products by description.
Input:
{ "descriptions": ["Mountain Dew", "eggs", "organic milk"]}Use case: Find specific products or categories.
2. search_offers
Section titled “2. search_offers”Search for available offers.
Input:
{ "query": "summer treats", "user_id": "user123", "limit": 200}Use case: Find relevant offers for a user.
3. search_nearby_offers
Section titled “3. search_nearby_offers”Search for offers near a location.
Input:
{ "user_id": "user123", "latitude": 37.7749, "longitude": -122.4194, "query": "coffee drinks"}Use case: Find offers at nearby stores.
4. get_user_purchase_history
Section titled “4. get_user_purchase_history”Get user’s past purchases with optional filtering.
Input:
{ "user_id": "user123", "start_time": "2024-01-01T00:00:00Z", # optional, RFC3339, defaults to 90 days ago "end_time": "2024-12-31T23:59:59Z", # optional, RFC3339, defaults to now "category": "snacks", # optional, natural language filter "brand": "coca cola" # optional, natural language filter}Use case: Understand user preferences and shopping patterns. Supports semantic search for category/brand filtering.
5. fetch_webpage
Section titled “5. fetch_webpage”Fetch and parse a webpage.
Input:
{ "url": "https://example.com", "depth": 0 # 0-2, prevents crawling}Use case: Extract content from web pages.
6. llm_feedback
Section titled “6. llm_feedback”Submit feedback about tools.
Input:
{ "message": "User wanted to search by brand"}Use case: Report feature requests or missing capabilities.
How to Enable
Section titled “How to Enable”In Agent Code
Section titled “In Agent Code”Pass MCP config when creating the agent:
from consumer_agent.agent import Agentfrom consumer_agent.factory import create_chat_modelfrom consumer_agent.utils.tools import build_mcp_toolsfrom consumer_agent.config import settings
# Build tools if MCP is configuredtools = []if settings.rover_mcp.server_url and settings.rover_mcp.authorization: tools = build_mcp_tools( server_url=settings.rover_mcp.server_url, auth_token=settings.rover_mcp.authorization, timeout=settings.rover_mcp.timeout )
# Create agent with toolsmodel = create_chat_model()agent = Agent(model, tools=tools)In FastAPI Service
Section titled “In FastAPI Service”MCP is automatically enabled if ROVER_MCP_AUTHORIZATION is set:
# From src/consumer_agent/api/main.py# Tools are created via factory.create_agent_from_config()# which checks settings.rover_mcp configurationagent = create_agent_from_config(agent_id="conversational")Tool Architecture
Section titled “Tool Architecture”Custom Tool Wrappers
Section titled “Custom Tool Wrappers”Each tool is a LangChain BaseTool wrapper (src/consumer_agent/utils/tools.py) that provides:
- Provider-agnostic: Works with any LLM, not just OpenAI
- Type safety: Pydantic schemas validate inputs
- Error handling: Catches and logs errors gracefully
- Async: Non-blocking tool execution
MCP Client
Section titled “MCP Client”JSON-RPC 2.0 client for server communication (src/consumer_agent/utils/mcp_client.py). Handles tool calls and tool listing.
Features:
- Auto-formats auth header (adds “Bearer” prefix)
- Constructs MCP endpoint URL (adds “/mcp” suffix)
- Handles JSON-RPC errors
- Logs all requests/responses
Usage Examples
Section titled “Usage Examples”Agent with MCP Tools
Section titled “Agent with MCP Tools”from consumer_agent.agent import Agentfrom consumer_agent.factory import create_chat_modelfrom consumer_agent.utils.tools import build_mcp_toolsfrom consumer_agent.config import settings
# Setuptools = build_mcp_tools( settings.rover_mcp.server_url, settings.rover_mcp.authorization, settings.rover_mcp.timeout)
model = create_chat_model()agent = Agent(model, tools=tools)
# Use agentmessages = [{"role": "user", "content": "Find offers for coffee"}]system_prompt = "You are a shopping assistant."
async for event in agent.stream(messages, system_prompt): if isinstance(event, ToolCallStartEvent): print(f"Calling: {event.tool_name}") elif isinstance(event, TextEvent): print(event.content)Check Available Tools
Section titled “Check Available Tools”from consumer_agent.utils.mcp_client import MCPClientfrom consumer_agent.config import settings
client = MCPClient( settings.rover_mcp.server_url, settings.rover_mcp.authorization, settings.rover_mcp.timeout)
# List tools from servertools = await client.list_tools()for tool in tools: print(f"- {tool['name']}: {tool['description']}")Call Tool Directly
Section titled “Call Tool Directly”from consumer_agent.utils.mcp_client import MCPClient
client = MCPClient(server_url, auth_token, timeout=90.0)
# Search for productsresult = await client.call_tool( "search_products", {"descriptions": ["coffee", "milk"]})print(result)Troubleshooting
Section titled “Troubleshooting”Error: ROVER_MCP_AUTHORIZATION environment variable not found
Section titled “Error: ROVER_MCP_AUTHORIZATION environment variable not found”MCP is optional. This is not an error if you don’t need tools.
To enable MCP:
- Get auth token from AWS Secrets Manager (see setup checklist)
- Add to
.env:ROVER_MCP_AUTHORIZATION=your-token
Error: MCPError: Unauthorized (401)
Section titled “Error: MCPError: Unauthorized (401)”Auth token is invalid or expired.
Fix:
- Retrieve fresh token from AWS Secrets Manager
- Update
.envwith new token - Restart application
Error: httpx.TimeoutException
Section titled “Error: httpx.TimeoutException”MCP server did not respond within timeout.
Fix:
# Increase timeout in settings.yamlrover_mcp: timeout: 120.0 # Increase from 90Tool calls fail with Error executing tool
Section titled “Tool calls fail with Error executing tool”Check MCP server status:
curl -H "Authorization: Bearer $ROVER_MCP_AUTHORIZATION" \ https://stage-partners-gateway.fetchrewards.com/rover-mcp/healthIf server is down, contact infrastructure team.
Agent doesn’t call tools
Section titled “Agent doesn’t call tools”Possible causes:
- Tools not bound: Verify tools passed to agent constructor
- System prompt: Prompt may discourage tool use
- Model limitations: Some models prefer not to use tools
Debug:
# Check if tools are loadedprint(f"Agent has {len(agent._tools)} tools")for tool in agent._tools: print(f" - {tool.name}")ImportError: No module named 'consumer_agent.utils.tools'
Section titled “ImportError: No module named 'consumer_agent.utils.tools'”Dependencies not installed or virtual environment not activated.
Fix:
uv syncsource .venv/bin/activateDisabling MCP
Section titled “Disabling MCP”To run without MCP:
- Remove from
.env:
# Delete or comment out:# ROVER_MCP_AUTHORIZATION=...- Agent still works:
# Without ROVER_MCP_AUTHORIZATION, no tools are loadedagent = create_agent_from_config(agent_id="conversational")# Agent has no tools but operates normally using LLM knowledgeThe agent operates normally without tools, using only its knowledge.
References
Section titled “References”- Setup Guide - Environment configuration
- Architecture Guide - Tool execution flow
- Development Guide - Testing with MCP