HotCRM Logo

MCP Integration Guide

How to build AI-powered CRM features using the Model Context Protocol (MCP) — tools, resources, prompts, orchestrations, and predictive models.

MCP Integration Guide

The Model Context Protocol (MCP) is the standard interface between AI models and HotCRM's business data. MCP enables AI agents to search records, read pipeline data, analyze deals, and take actions — all through a structured, type-safe protocol.

HotCRM implements three MCP primitives plus higher-level AI capabilities:

PrimitivePurposeExample
ToolsActions the AI can performSearch accounts, update deal stage
ResourcesRead-only data the AI can accessPipeline summary, forecast data
PromptsPre-built prompt templatesDeal analysis, win/loss review
OrchestrationsMulti-step AI pipelinesSales intelligence workflow
Predictive ModelsML model definitionsLead scoring, churn prediction

Why MCP for CRM?

Traditional CRM integrations require custom API code for every AI feature. MCP provides a universal protocol that any AI model can use:

  • Structured tool calling: AI models invoke CRM operations through typed schemas, not free-form API calls
  • Context injection: Resources give AI models real-time access to pipeline, forecast, and territory data
  • Reusable prompts: Pre-built templates encode domain expertise (sales methodology, support playbooks)
  • Composability: Tools, resources, and prompts combine into orchestrations for complex workflows

MCP Tools

Tools are operations that AI agents can invoke. Each tool has a name, description, and a JSON Schema defining its input parameters.

Defining a Tool

import { MCPToolSchema } from '@objectstack/spec/ai';

export const SearchAccountsTool = MCPToolSchema.parse({
  name: 'search_accounts',
  description: 'Search CRM accounts by name, industry, or revenue range',
  inputSchema: {
    type: 'object',
    properties: {
      query: { type: 'string', description: 'Search term for account name' },
      industry: { type: 'string', description: 'Filter by industry vertical' },
      minRevenue: { type: 'number', description: 'Minimum annual revenue threshold' },
    },
    required: ['query']
  }
});

CRM Tool Catalog

HotCRM ships 24 MCP tools across all clouds:

CloudToolDescription
Salessearch_accountsSearch accounts by name, industry, or revenue
Salesget_opportunityRetrieve full opportunity details
Salesupdate_deal_stageMove an opportunity between pipeline stages
Salescreate_activityLog a call, email, meeting, or task
Financecreate_invoiceGenerate an invoice from a contract
Financerecord_paymentRecord a payment against an invoice
Supportsearch_casesFind support cases by status or priority
Supportescalate_caseEscalate a case to a higher tier
Marketingcreate_campaignSet up a new marketing campaign
Marketingadd_campaign_membersAdd leads/contacts to a campaign
Productssearch_productsSearch the product catalog
Productsgenerate_quoteGenerate a quote with pricing rules
HRsearch_employeesFind employees by department or role
HRcreate_job_requisitionOpen a new hiring requisition

Tool Implementation Pattern

Tools follow a two-file pattern: schema definition (.mcp.ts) and handler (.action.ts):

packages/crm/src/
├── crm_mcp_tools.mcp.ts        # Tool schemas (what the AI sees)
├── actions/
│   ├── ai_smart_briefing.action.ts  # Tool handler (what runs)
│   └── deal_copilot.action.ts

The .mcp.ts file defines the contract; the .action.ts file implements the business logic using ObjectQL:

// In the action handler — always use ObjectQL, never raw SQL
const accounts = await broker.find('account', {
  filters: [
    ['name', 'contains', query],
    ['industry', '=', industry]
  ],
  fields: ['name', 'industry', 'annual_revenue', 'owner'],
  limit: 20
});

MCP Resources

Resources expose read-only data to AI models for context. Unlike tools, resources are passive — they provide information the AI can reference when generating responses.

Defining a Resource

import { MCPResourceSchema } from '@objectstack/spec/ai';

export const PipelineSummaryResource = MCPResourceSchema.parse({
  uri: 'hotcrm://crm/pipeline-summary',
  name: 'Pipeline Summary',
  description: 'Current sales pipeline with stage distribution and velocity metrics',
  mimeType: 'application/json'
});

CRM Resource Catalog

CloudResourceURIDescription
SalesAccount Listhotcrm://crm/accountsPaginated accounts with health scores
SalesPipeline Summaryhotcrm://crm/pipeline-summaryStage distribution and velocity
SalesForecast Datahotcrm://crm/forecastRevenue forecasts by period/segment
SalesTerritory Maphotcrm://crm/territoriesTerritory assignments and quotas
SupportCase Queuehotcrm://support/case-queueOpen cases by priority and SLA status
SupportKnowledge Basehotcrm://support/knowledgeArticle summaries for case resolution
FinanceAR Aginghotcrm://finance/ar-agingAccounts receivable aging summary
HROrg Charthotcrm://hr/org-chartDepartment structure and headcount

Resource URI Convention

All HotCRM resources use the hotcrm:// URI scheme:

hotcrm://{cloud}/{resource-name}

Examples:

  • hotcrm://crm/pipeline-summary
  • hotcrm://support/case-queue
  • hotcrm://finance/ar-aging

MCP Prompts

Prompts are pre-built templates that encode domain expertise. They accept arguments and generate structured prompts for AI models.

Defining a Prompt

import { MCPPromptSchema } from '@objectstack/spec/ai';

export const DealAnalysisPrompt = MCPPromptSchema.parse({
  name: 'deal_analysis',
  description: 'Analyze deal health with risk assessment and close probability',
  arguments: [
    {
      name: 'opportunity_id',
      description: 'The opportunity record to analyze',
      required: true
    }
  ]
});

Prompt Catalog by Cloud

Sales Prompts (crm_prompts.mcp.ts):

PromptPurpose
deal_analysisRisk assessment and close probability for an opportunity
customer_360_summaryHolistic account view across all touchpoints
next_best_actionRecommend the optimal next step for a deal
win_loss_analysisExtract learnings from closed won/lost deals

Support Prompts (support_prompts.mcp.ts):

PromptPurpose
case_resolutionSuggest resolution steps based on case history
escalation_analysisDetermine if a case needs escalation
customer_sentimentAnalyze sentiment from case communications

HR Prompts (hr_prompts.mcp.ts):

PromptPurpose
candidate_evaluationEvaluate candidate fit against job requirements
employee_developmentSuggest development plans based on performance
retention_riskAssess employee flight risk and recommend actions

AI Orchestrations

Orchestrations chain multiple AI tasks into multi-step pipelines triggered by business events. Each step can use different models, and results flow between steps.

Defining an Orchestration

import { AIOrchestrationSchema } from '@objectstack/spec/ai';

export const SalesOrchestration = AIOrchestrationSchema.parse({
  name: 'sales_deal_pipeline',
  label: 'Sales Deal Intelligence Pipeline',
  description: 'Multi-step AI analysis triggered when an opportunity changes stage',

  trigger: {
    type: 'record_change',
    object: 'opportunity',
    field: 'stage'
  },

  steps: [
    {
      id: 'classify_risk',
      type: 'ai_task',
      model: 'gpt-4o',
      prompt: 'Classify this deal risk as low, medium, or high based on: {{deal_summary}}',
      outputVariable: 'risk_level'
    },
    {
      id: 'summarize_deal',
      type: 'ai_task',
      model: 'gpt-4o',
      prompt: 'Generate a 3-sentence executive summary for: {{opportunity.name}}',
      outputVariable: 'deal_summary_text'
    },
    {
      id: 'recommend_action',
      type: 'ai_task',
      model: 'gpt-4o',
      prompt: 'Based on risk={{risk_level}}, recommend the single best next action',
      outputVariable: 'recommended_action'
    }
  ],

  postActions: [
    {
      type: 'fieldUpdate',
      object: 'opportunity',
      field: 'risk_level',
      value: '{{classify_risk.output}}'
    },
    {
      type: 'emailAlert',
      condition: "risk_level = 'high'",
      template: 'high_risk_deal_alert',
      recipients: ['${opportunity.owner.email}', '${opportunity.owner.manager.email}']
    }
  ],

  execution: {
    mode: 'sequential',
    timeoutSeconds: 120
  }
});

Available Orchestrations

OrchestrationTriggerStepsCloud
Sales Deal PipelineOpportunity stage changeRisk classify → Summarize → RecommendSales
Support Triage PipelineNew case createdCategorize → Sentiment → Suggest resolution → Draft responseSupport

Files: packages/ai/src/sales_orchestration.orchestration.ts, packages/ai/src/support_orchestration.orchestration.ts


Predictive Models

Predictive models define machine learning configurations for scoring, classification, and forecasting. The metadata describes features, training parameters, and deployment settings — the runtime handles model training and inference.

Defining a Predictive Model

import { PredictiveModelSchema } from '@objectstack/spec/ai';

export const LeadScoringModel = PredictiveModelSchema.parse({
  name: 'lead_scoring',
  label: 'Lead Conversion Predictor',
  description: 'Gradient-boosting classifier predicting lead-to-opportunity conversion',
  object: 'lead',
  target: {
    field: 'is_converted',
    type: 'binary_classification'
  },
  features: [
    { field: 'industry', type: 'categorical' },
    { field: 'company_size', type: 'numerical' },
    { field: 'lead_source', type: 'categorical' },
    { field: 'engagement_score', type: 'numerical' },
    { field: 'email_opens', type: 'numerical' },
    { field: 'website_visits', type: 'numerical' },
  ],
  training: {
    algorithm: 'gradient_boosting',
    splitRatio: { train: 0.7, validation: 0.15, test: 0.15 },
    crossValidation: { folds: 5 },
    minRecords: 5000
  }
});

Model Catalog

ModelObjectTypeKey Features
Lead ScoringleadBinary classificationIndustry, company size, engagement, email opens, website visits
Churn PredictionaccountBinary classificationActivity recency, support tickets, satisfaction, contract end, usage trend
Deal ForecastopportunityBinary classificationStage, amount, days in stage, activity count, competitors, discount

Files: packages/ai/src/lead_scoring.predictive.ts, packages/ai/src/churn_prediction.predictive.ts, packages/ai/src/deal_forecast.predictive.ts


Putting It All Together

A complete AI-powered CRM workflow combines all MCP primitives:

  1. Resource provides context: Pipeline summary + account data
  2. Prompt structures the request: "Analyze this deal's risk"
  3. Tool takes action: Update the deal stage, log an activity
  4. Orchestration chains steps: Classify → Summarize → Recommend → Notify
  5. Predictive Model scores records: Lead conversion probability
┌─────────────┐     ┌──────────────┐     ┌─────────────┐
│  Resources   │────▶│  AI Agent    │────▶│   Tools     │
│ (read data)  │     │ (reasoning)  │     │ (take action)│
└─────────────┘     └──────┬───────┘     └─────────────┘

                    ┌──────▼───────┐
                    │   Prompts    │
                    │ (templates)  │
                    └──────────────┘

File Organization

All MCP metadata lives alongside the business objects it serves:

packages/crm/src/
├── account.object.ts              # Data model
├── crm_mcp_tools.mcp.ts          # MCP tools (search, update, create)
├── crm_mcp_resources.mcp.ts      # MCP resources (pipeline, forecast)
├── crm_prompts.mcp.ts            # MCP prompts (deal analysis, next action)
├── actions/
│   ├── ai_smart_briefing.action.ts    # Tool handler
│   └── deal_copilot.action.ts         # Tool handler

packages/ai/src/
├── sales_orchestration.orchestration.ts  # Multi-step pipeline
├── lead_scoring.predictive.ts            # ML model definition
├── churn_prediction.predictive.ts        # ML model definition
└── deal_forecast.predictive.ts           # ML model definition

Next steps: See the Metadata Types Reference for the complete catalog of all HotCRM metadata types.

On this page