Add CRM context to an MCP search agent by querying your CRM for account data before or after search calls, then merging the CRM context with search results to produce more relevant, account-aware responses. MCP agents with search tools return generic results that lack customer-specific context. By enriching search results with CRM data like deal stage, past interactions, and account size, the agent can tailor its recommendations and prioritize information that matters to the specific account being discussed.
Prerequisites
- Python 3.8+ installed
- requests library installed
- A Scavio API key from scavio.dev
- CRM data accessible via API or local file
Walkthrough
Step 1: Load CRM account data
Pull account context from your CRM to enrich search results.
import os, requests, json
API_KEY = os.environ['SCAVIO_API_KEY']
# Simulated CRM data (replace with your CRM API call)
def load_crm_account(account_name: str) -> dict:
# In production: requests.get(f'{CRM_API}/accounts?name={account_name}')
crm_data = {
'Acme Corp': {
'deal_stage': 'negotiation',
'deal_value': 50000,
'industry': 'manufacturing',
'size': '500-1000 employees',
'last_contact': '2026-04-15',
'notes': 'Interested in automation tools. Key pain point: manual data entry.',
},
'Beta Inc': {
'deal_stage': 'discovery',
'deal_value': 25000,
'industry': 'saas',
'size': '50-200 employees',
'last_contact': '2026-05-01',
'notes': 'Evaluating search APIs for their product. Comparing with SerpAPI.',
},
}
return crm_data.get(account_name, {})
account = load_crm_account('Acme Corp')
print(f"Stage: {account.get('deal_stage')}, Industry: {account.get('industry')}")Step 2: Search with account context
Use CRM context to refine search queries for more relevant results.
def contextual_search(query: str, account: dict) -> list:
"""Search with CRM context to get industry-relevant results."""
industry = account.get('industry', '')
refined_query = f'{query} {industry}' if industry else query
resp = requests.post('https://api.scavio.dev/api/v1/search',
headers={'x-api-key': API_KEY},
json={'platform': 'google', 'query': refined_query}, timeout=15)
results = resp.json().get('organic_results', [])
return [{
'title': r.get('title', ''),
'url': r.get('link', ''),
'snippet': r.get('snippet', ''),
} for r in results[:5]]
account = load_crm_account('Acme Corp')
results = contextual_search('automation tools', account)
for r in results:
print(f" {r['title'][:50]}")Step 3: Merge CRM and search data
Combine CRM account data with search results into a unified context block.
def merge_context(account_name: str, query: str) -> dict:
account = load_crm_account(account_name)
results = contextual_search(query, account)
return {
'account': {
'name': account_name,
'deal_stage': account.get('deal_stage', 'unknown'),
'industry': account.get('industry', ''),
'notes': account.get('notes', ''),
},
'search_results': results,
'context_type': 'enriched' if account else 'search_only',
}
merged = merge_context('Acme Corp', 'automation tools')
print(f"Context type: {merged['context_type']}")
print(f"Deal stage: {merged['account']['deal_stage']}")
print(f"Search results: {len(merged['search_results'])}")Step 4: Format for MCP agent
Structure the combined context for injection into the MCP agent's tool response.
def format_mcp_response(merged: dict) -> str:
parts = []
acct = merged.get('account', {})
if acct.get('deal_stage') != 'unknown':
parts.append('ACCOUNT CONTEXT:')
parts.append(f" Company: {acct.get('name', '')}")
parts.append(f" Deal Stage: {acct.get('deal_stage', '')}")
parts.append(f" Industry: {acct.get('industry', '')}")
if acct.get('notes'):
parts.append(f" Notes: {acct['notes']}")
parts.append('')
parts.append('SEARCH RESULTS:')
for i, r in enumerate(merged.get('search_results', []), 1):
parts.append(f'{i}. {r["title"]}')
if r.get('snippet'):
parts.append(f' {r["snippet"][:150]}')
return '\n'.join(parts)
response = format_mcp_response(merged)
print(response[:500])Step 5: Test with MCP tool call
Simulate an MCP tool call that combines CRM lookup with search.
def mcp_search_tool(params: dict) -> dict:
"""MCP tool handler for CRM-enriched search."""
query = params.get('query', '')
account_name = params.get('account', '')
if not query:
return {'error': 'query is required'}
merged = merge_context(account_name, query)
formatted = format_mcp_response(merged)
return {
'content': [{'type': 'text', 'text': formatted}],
'isError': False,
}
# Test the MCP tool
result = mcp_search_tool({'query': 'automation tools', 'account': 'Acme Corp'})
print(result['content'][0]['text'][:400])
# Test without account
result2 = mcp_search_tool({'query': 'search api comparison', 'account': ''})
print(f'\nWithout account: {len(result2["content"][0]["text"])} chars')Python Example
import requests, os
H = {'x-api-key': os.environ['SCAVIO_API_KEY']}
def crm_search(query, industry=''):
refined = f'{query} {industry}'.strip()
data = requests.post('https://api.scavio.dev/api/v1/search', headers=H,
json={'platform': 'google', 'query': refined}).json()
return [{'title': r['title'], 'snippet': r.get('snippet', '')[:80]}
for r in data.get('organic_results', [])[:3]]
print(crm_search('automation tools', 'manufacturing'))JavaScript Example
const H = {'x-api-key': process.env.SCAVIO_API_KEY, 'Content-Type': 'application/json'};
async function crmSearch(query, industry = '') {
const r = await fetch('https://api.scavio.dev/api/v1/search', {
method: 'POST', headers: H,
body: JSON.stringify({platform: 'google', query: `${query} ${industry}`.trim()})
});
return ((await r.json()).organic_results || []).slice(0, 3)
.map(r => ({title: r.title, snippet: (r.snippet || '').slice(0, 80)}));
}
crmSearch('automation tools', 'manufacturing').then(console.log);Expected Output
An MCP search agent enriched with CRM account context that delivers industry-specific, deal-stage-aware search results for more relevant agent responses.