npm package: @olbrain/lead-generation-mcp
Description: Lead Generation MCP Server with Google Forms integration and session-aware lead management
Author: Alchemist
Latest version: 1.0.9

# Lead Generation MCP Server

AI-powered lead management from Google Forms with session context awareness and intelligent follow-up capabilities.

## Overview

This MCP server provides AI agents with access to Google Forms lead data through **8 tools** covering the complete lead management lifecycle:

- **Lead Discovery**: Fetch, list, and search leads from Google Sheets
- **Session-Aware Matching**: Automatically match current user to their lead record
- **Lead Management**: Update status, notes, and lead data
- **Duplicate Detection**: Identify and manage duplicate submissions
- **Lead Creation**: Add new leads discovered through conversation

## Features

**8 Complete Lead Management Tools**

**Read Operations (5 tools)**
- `gforms_list_leads` - Fetch all leads with filtering and sorting
- `gforms_get_current_lead` - Get current session user's lead (primary function)
- `gforms_search_leads` - Search leads by keyword across all fields
- `gforms_get_lead_interests` - Extract structured interest data
- `gforms_detect_duplicates` - Find duplicate leads by email/phone

**Write Operations (3 tools)**
- `gforms_update_lead_status` - Update follow-up status and notes
- `gforms_update_lead_data` - Update any field in lead's Sheet row
- `gforms_add_lead` - Add new lead who didn't fill form

## Key Capabilities

- **Session Context Awareness**: Automatically matches the current user (via phone/email) to their lead record for personalized conversations
- **Firestore Caching**: Configurable caching (default 5 min) reduces API calls and improves performance
- **Status Tracking**: Track lead follow-up status (new, contacted, qualified, converted, not_interested)
- **Duplicate Management**: Non-destructive duplicate detection with auto-marking capability
- **Interest Extraction**: AI-powered analysis of form responses to identify interests and pain points

## Architecture

- **Protocol**: MCP JSON-RPC 2.0 over stdio
- **API**: Google Sheets API v4 (via gspread)
- **Authentication**: Service Account with Sheet access
- **Caching**: Firestore (optional) for performance optimization
- **State Management**: Session-aware with agent_id and session_id context
- **Deployment**: Compatible with OpenAI Responses API via mcp-service-template
- **Language**: Python 3.10+

## Installation

### Requirements

- Python 3.10 or higher
- Node.js 16+ (for npx deployment)
- Google Service Account with Sheets API enabled
- Google Sheet shared with service account email
- Firestore (optional, for caching and status tracking)

### Via NPM (Recommended)

```bash
npx -y @olbrain/lead-generation-mcp@latest
```

### Local Development

```bash
cd mcp_servers/lead-generation

# Install Python dependencies
pip install -r requirements.txt

# Run server directly
python3 src/server.py
```

## Configuration

### Google Service Account Setup

1. Go to [Google Cloud Console](https://console.cloud.google.com/)
2. Create or select a project
3. Enable Google Sheets API
4. Go to IAM & Admin → Service Accounts
5. Click "Create Service Account"
6. Name: "Lead Generation MCP"
7. Click "Create and Continue"
8. Grant role: "Editor" (or custom role with sheets.spreadsheets.readonly)
9. Click "Done"
10. Click on the service account email
11. Go to "Keys" tab
12. Click "Add Key" → "Create new key" → "JSON"
13. Download and save the JSON file
14. **Important**: Copy the service account email (looks like: your-sa@project-id.iam.gserviceaccount.com)

### Google Sheets Setup

1. Open your Google Form responses Sheet
2. Click "Share" button (top right)
3. Paste the service account email from step 14 above
4. Grant "Editor" or "Viewer" access (Editor if you want write operations)
5. Click "Send"
6. Copy the Spreadsheet ID from the URL:
   - URL format: `https://docs.google.com/spreadsheets/d/{SPREADSHEET_ID}/edit`
   - The ID is the long string between `/d/` and `/edit`

### Environment Variables

The server requires this environment variable:

```bash
LEAD_GEN_CONFIG='{
  "service_account_json": {...},
  "spreadsheet_id": "your-spreadsheet-id",
  "sheet_name": "Form Responses 1",
  "email_column": "Email Address",
  "phone_column": "Phone Number",
  "name_column": "Name",
  "cache_duration_minutes": "5"
}'
```

**Configuration Fields:**
- `service_account_json` (required): Complete JSON content from service account key file
- `spreadsheet_id` (required): Google Sheets ID from URL
- `sheet_name` (optional): Sheet tab name, default "Form Responses 1"
- `email_column` (optional): Column header for email field
- `phone_column` (optional): Column header for phone field
- `name_column` (optional): Column header for name field
- `cache_duration_minutes` (optional): Cache TTL in minutes, default 5

## Usage with mcp-service-template

The server is designed to be deployed via Alchemist's mcp-service-template:

1. **User enables** Lead Generation in project-dashboard
2. **tool-manager syncs** configuration to Firestore
3. **deploy_job.py** deploys mcp-service-template for agent
4. **MCPManager** spawns this server via `npx @olbrain/lead-generation-mcp`
5. **OpenAI Responses API** calls tools via JSON-RPC

## Available Tools (8 Total)

### Read Operations

#### gforms_list_leads
Fetch all leads from Google Sheets with optional filtering and sorting.
- Parameters: `limit`, `status`, `order_by`
- Returns: Array of lead objects with all form fields

#### gforms_get_current_lead
Get lead information for the current session user. **Primary tool for personalized conversations.**
- Parameters: `identifier_field` (email or phone)
- Returns: Lead object matching current user's phone/email
- Automatically uses session context to match user

#### gforms_search_leads
Search for leads by keyword across all form fields.
- Parameters: `query` (required), `fields`, `limit`
- Returns: Array of matching lead objects

#### gforms_get_lead_interests
Extract and structure interest/preference data from a lead's form submission.
- Parameters: `lead_id` (optional, defaults to current user)
- Returns: Structured interest data for personalized follow-up

#### gforms_detect_duplicates
Detect duplicate leads based on email or phone matching.
- Parameters: `match_criteria`, `auto_merge`
- Returns: List of duplicate groups with lead IDs

### Write Operations

#### gforms_update_lead_status
Update follow-up status and notes for a lead.
- Parameters: `lead_id` (optional), `status` (required), `notes`
- Status values: contacted, qualified, converted, not_interested
- Session-scoped: Can only update current user's lead without lead_id

#### gforms_update_lead_data
Update any field in a lead's Google Sheet row.
- Parameters: `lead_id` (optional), `updates` (required)
- Updates can include any column: Email, Phone, Name, custom fields
- Tracks update timestamps and contact frequency

#### gforms_add_lead
Add a new lead who didn't fill out the form.
- Parameters: `email`, `phone`, `name`, `interests`, `additional_data`
- Automatically checks for duplicates before adding
- Useful for leads discovered through conversation

## Session Context

The server uses `session_id` and `agent_id` from environment variables to enable session-aware operations:

```bash
SESSION_ID=abc123
AGENT_ID=agent-xyz
```

These are automatically injected by the ToolRegistry when running in the Alchemist platform.

## Error Handling

The server returns structured error responses:

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "error": {
    "code": -32603,
    "message": "Tool execution failed: error details"
  }
}
```

Common error codes:
- `-32601`: Tool not found
- `-32602`: Invalid parameters
- `-32603`: Tool execution failed

## Testing

For local testing without Alchemist platform:

```bash
# Set environment variable
export LEAD_GEN_CONFIG='{"service_account_json": {...}, "spreadsheet_id": "your-id"}'
export SESSION_ID="test-session"
export AGENT_ID="test-agent"

# Run server
python3 src/server.py

# Send JSON-RPC request via stdin
echo '{"jsonrpc":"2.0","method":"initialize","params":{},"id":1}' | python3 src/server.py
```

## License

MIT License - see [LICENSE](../../LICENSE) for details

## Related Documentation

- [Google Forms Leads Tool](../../tools/google_forms_leads/) - The underlying tool implementation
- [MCP Standards](../../MCP_STANDARDS.md) - MCP server development standards
- [Tool Standards](../../TOOL_STANDARDS.md) - Tool suite format specification