MCP for HubSpot: Marketing Analytics Through Natural Language
Build an MCP server for HubSpot to enable Claude and AI assistants to answer marketing questions natively. Technical guide for data teams.
Understanding the Model Context Protocol and HubSpot Integration
The Model Context Protocol (MCP) represents a fundamental shift in how AI assistants interact with business data. Rather than forcing users to manually extract information from CRM systems, MCP creates a standardized bridge that lets Claude, GPT-4, and other large language models query HubSpot data directly using natural language. This isn’t just a convenience layer—it’s a structural change that eliminates friction between your analytics infrastructure and the people who need answers.
When you build an MCP server for HubSpot, you’re essentially creating a secure, standardized interface that translates natural language questions into HubSpot API calls. A marketing leader can ask “What’s our win rate for enterprise deals closed in Q4?” and Claude will fetch the relevant data, perform calculations, and return a conversational answer with context. No SQL. No dashboard navigation. No waiting for a data analyst to run a custom report.
This capability becomes especially powerful when combined with D23’s managed Apache Superset platform, which can ingest HubSpot data via API and layer AI-powered text-to-SQL capabilities on top. Teams get both conversational analytics (through MCP) and self-serve dashboard exploration (through Superset), creating a complete analytics experience that scales across your organization.
Why MCP Matters for Marketing Teams
Marketing analytics has traditionally been bottlenecked by tooling fragmentation. Your data lives in HubSpot, your performance metrics live in Google Analytics or Mixpanel, your customer feedback lives in Slack or Zendesk, and your dashboards live in Tableau or Looker. Each tool requires separate login credentials, different query languages, and distinct mental models. When a VP of Marketing needs an answer at 9 AM on a Monday, they either wait for a data analyst or make a decision with incomplete information.
MCP flattens this friction. By exposing HubSpot data through a standardized protocol, you enable any AI assistant to become an on-demand analytics engine. According to Anthropic’s announcement of the Model Context Protocol, MCP was designed specifically to solve this problem—providing AI agents with secure, standardized access to tools and data sources without requiring custom integrations for each use case.
For marketing teams specifically, this means:
- Real-time reporting without dashboards: Ask Claude about pipeline velocity, conversion rates, or campaign ROI in natural language. No need to log into HubSpot, navigate to reports, or wait for a dashboard to load.
- Contextual analysis: The AI can pull data from multiple sources (HubSpot, email performance, customer success metrics) and synthesize insights in a single conversation.
- Faster decision-making: Instead of scheduling a data request with a 24-48 hour turnaround, marketing leaders get answers in seconds.
- Reduced data literacy burden: Non-technical marketers can ask complex analytical questions without learning SQL or dashboard software.
When you layer this on top of D23’s embedded analytics capabilities, you can also embed these AI-powered insights directly into your product or internal tools, creating a seamless analytics experience for teams across your organization.
The Technical Architecture: Building Your MCP Server
An MCP server for HubSpot is fundamentally a stateless application that listens for requests from Claude (or another AI client), translates natural language intent into HubSpot API calls, and returns structured data back to the AI. The architecture has three key layers:
The MCP Server Layer
Your MCP server acts as the intermediary between Claude and HubSpot. It implements the MCP specification, which means it exposes “tools” that Claude can call. Each tool corresponds to a logical capability—querying deals, listing contacts, fetching campaign performance, etc.
The server runs as a separate process (typically Node.js, Python, or Go) and communicates with Claude via standard input/output (stdio) or HTTP. When Claude encounters a question that requires data, it examines the available tools, selects the appropriate one, and sends a structured request to your MCP server.
For example, if a user asks “How many deals are in our sales pipeline right now?”, Claude will:
- Recognize that this question requires data from HubSpot
- Call your MCP server’s
get_deals_by_stagetool - Pass parameters like
stage: "negotiation"andlimit: 100 - Receive structured JSON with deal data
- Synthesize a natural language response
The HubSpot API Integration
Your MCP server communicates with HubSpot via its REST API. HubSpot’s API is comprehensive and well-documented, exposing endpoints for contacts, deals, companies, tickets, and engagement data. You’ll authenticate using a private app token (stored securely in environment variables) and make HTTP requests to fetch or update data.
The key is to design your MCP tools in a way that maps cleanly to HubSpot’s API structure while abstracting away unnecessary complexity. Instead of exposing the raw API endpoints, you create higher-level tools that answer specific business questions.
According to the official HubSpot developer documentation on integrating AI tools with the HubSpot MCP server, HubSpot itself provides native MCP support, which means you can either build your own server or use HubSpot’s pre-built MCP server. The pre-built option is faster to implement but less customizable. Building your own gives you full control over which data is exposed and how it’s processed.
The Claude Client
Claude (or GPT-4, or another LLM) acts as the orchestrator. It understands natural language, determines which tools are needed to answer a question, calls your MCP server, and synthesizes the results into a conversational response. Claude handles all the reasoning—you don’t need to write custom logic to route questions or parse intent.
Setting Up Your MCP Server: A Practical Guide
Let’s walk through the process of building a basic MCP server for HubSpot that exposes marketing analytics capabilities.
Step 1: Define Your Tools
Start by listing the specific questions your marketing team needs answered. These become your tools. Examples:
get_pipeline_summary: Returns deal counts by stage, average deal size, and sales cycle lengthget_contact_metrics: Returns contact count, segmentation data, and engagement metricsget_campaign_performance: Returns email open rates, click rates, and conversion metricsget_deal_analytics: Returns win rates, loss reasons, and deal velocity by product lineget_contact_by_email: Looks up a specific contact and returns their engagement history
Each tool should be narrowly scoped and return data in a consistent JSON format. Avoid tools that are too broad (like “query any HubSpot data”) because they’re harder to document and more prone to errors.
Step 2: Set Up Your Development Environment
You’ll need:
- Node.js 16+ (or Python 3.8+ if you prefer)
- A HubSpot account with API access and a private app token
- The MCP SDK (Anthropic provides SDKs for Node.js and Python)
- A local development environment where you can run and test the server
Create a new project directory and install dependencies:
mkdir hubspot-mcp-server
cd hubspot-mcp-server
npm init -y
npm install @modelcontextprotocol/sdk axios dotenv
Step 3: Implement Tool Handlers
Create a file called tools.js that defines your tool handlers. Each handler is an async function that takes parameters, calls the HubSpot API, and returns data:
const axios = require('axios');
const HUBSPOT_API_BASE = 'https://api.hubapi.com';
const HUBSPOT_TOKEN = process.env.HUBSPOT_PRIVATE_APP_TOKEN;
const headers = {
'Authorization': `Bearer ${HUBSPOT_TOKEN}`,
'Content-Type': 'application/json'
};
async function getPipelineSummary() {
try {
const response = await axios.get(
`${HUBSPOT_API_BASE}/crm/v3/objects/deals`,
{
params: {
limit: 100,
properties: ['dealstage', 'amount', 'closedate']
},
headers
}
);
const deals = response.data.results;
const summary = {};
deals.forEach(deal => {
const stage = deal.properties.dealstage || 'unknown';
if (!summary[stage]) {
summary[stage] = { count: 0, totalValue: 0, avgValue: 0 };
}
summary[stage].count += 1;
summary[stage].totalValue += parseFloat(deal.properties.amount || 0);
});
Object.keys(summary).forEach(stage => {
summary[stage].avgValue = summary[stage].totalValue / summary[stage].count;
});
return { success: true, data: summary };
} catch (error) {
return { success: false, error: error.message };
}
}
module.exports = { getPipelineSummary };
This is a simplified example. In production, you’d add error handling, caching, rate limiting, and more sophisticated data processing.
Step 4: Create the MCP Server
Create a file called server.js that initializes the MCP server and registers your tools:
const { Server } = require('@modelcontextprotocol/sdk/server/index.js');
const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js');
const { CallToolRequestSchema, ListToolsRequestSchema, TextContent } = require('@modelcontextprotocol/sdk/types.js');
const { getPipelineSummary } = require('./tools.js');
const server = new Server({
name: 'hubspot-mcp-server',
version: '1.0.0'
});
const tools = [
{
name: 'get_pipeline_summary',
description: 'Returns a summary of deals by stage, including count and average deal value',
inputSchema: {
type: 'object',
properties: {},
required: []
}
}
];
server.setRequestHandler(ListToolsRequestSchema, async () => {
return { tools };
});
server.setRequestHandler(CallToolRequestSchema, async (request) => {
if (request.params.name === 'get_pipeline_summary') {
const result = await getPipelineSummary();
return {
content: [{
type: 'text',
text: JSON.stringify(result, null, 2)
}]
};
}
return { content: [{ type: 'text', text: 'Tool not found' }] };
});
const transport = new StdioServerTransport();
server.connect(transport);
Step 5: Test with Claude
Once your server is running, you can test it with Claude through the Claude API. You’ll need to configure Claude to use your MCP server as a tool source. The exact process depends on your Claude integration method (API, desktop app, etc.), but the general approach is:
- Start your MCP server:
node server.js - Configure Claude to connect to your server
- Ask Claude a question like “What’s our pipeline summary?”
- Claude will call your MCP server, receive the data, and synthesize a response
Advanced Patterns: Combining MCP with Managed Analytics
MCP excels at conversational, ad-hoc analytics. But for recurring reporting, dashboards, and complex multi-step analyses, you need a complementary tool. This is where D23’s managed Apache Superset platform becomes valuable.
Here’s a powerful architecture:
- MCP server: Handles conversational queries, real-time data lookups, and quick answers. Claude asks “What’s our win rate?” and gets an immediate response.
- Apache Superset: Handles dashboard creation, scheduled reports, and complex analytical workflows. Teams build dashboards that visualize HubSpot data, set up alerts, and share insights across the organization.
- Data consulting: D23 provides expert guidance on analytics strategy, ensuring your MCP tools and dashboards align with business objectives.
You can even create tools in your MCP server that reference Superset dashboards. For example, a tool called get_campaign_dashboard_link could return a pre-filtered Superset dashboard URL that shows campaign performance for a specific timeframe.
According to CData’s overview of the MCP Server for HubSpot, this kind of integration is becoming standard—AI assistants need both conversational access to data and the ability to reference structured, pre-built analytics.
Security and Authentication
When building an MCP server that connects to HubSpot, security is critical. You’re creating a gateway that exposes customer data, so you need to implement proper controls.
Authentication Best Practices
- Use private app tokens: Store your HubSpot API token in environment variables, never in code or version control.
- Implement rate limiting: HubSpot has API rate limits. Implement exponential backoff and request queuing in your MCP server to avoid hitting limits.
- Validate all inputs: Sanitize parameters passed from Claude to prevent injection attacks or unintended data exposure.
- Log all requests: Maintain an audit trail of what data was accessed and when. This is critical for compliance and debugging.
Data Access Control
Consider implementing role-based access control (RBAC) in your MCP server. For example:
- Sales leaders can access deal data and pipeline metrics
- Marketing leaders can access contact data and campaign performance
- Executives can access high-level summaries but not individual contact details
You can implement this by passing user context to your MCP server and checking permissions before returning data.
Real-World Examples: Questions Your MCP Server Can Answer
Once your MCP server is live, here are the types of questions marketing teams can ask Claude:
Pipeline and Revenue Analytics
- “What’s our pipeline by product line for the next quarter?”
- “How many deals are stalled in negotiation, and what’s the average value?”
- “What’s our win rate for enterprise deals vs. SMB deals?”
- “Which sales reps have the longest average sales cycle?”
Contact and Segmentation Analytics
- “How many contacts do we have in the healthcare vertical?”
- “What’s the engagement rate for contacts we added in the last 30 days?”
- “Which companies have the most contacts in our database?”
Campaign Performance
- “What was the open rate for last week’s email campaign?”
- “How many leads did we generate from the webinar?”
- “Which content pieces have the highest click-through rate?”
Customer Success Metrics
- “How many customers are at risk of churn based on recent engagement?”
- “What’s our NPS score trend over the last quarter?”
- “Which customer segments have the highest lifetime value?”
Each of these questions, which would normally require a data analyst to run a custom report, now gets answered in seconds through natural conversation with Claude.
Comparing MCP to Traditional BI Tools
When evaluating whether to build an MCP server, it’s helpful to understand how it compares to traditional business intelligence platforms.
MCP for HubSpot vs. Looker: Looker is a powerful BI platform that can connect to HubSpot and create dashboards. But Looker requires users to navigate a UI and often requires SQL knowledge for custom queries. MCP enables natural language access without any UI navigation.
MCP for HubSpot vs. Tableau: Similar to Looker, Tableau excels at creating complex visualizations and dashboards. But it’s not designed for conversational analytics. MCP fills that gap.
MCP for HubSpot vs. Metabase: Metabase is more lightweight than Looker or Tableau and has some natural language capabilities. But Metabase is primarily a dashboard tool, not a conversational analytics engine. MCP is conversational-first.
MCP for HubSpot vs. Preset: Preset is a managed version of Apache Superset. Like Superset, it’s excellent for dashboards and self-serve analytics. MCP is complementary—you’d use Preset or D23’s managed Superset for dashboards and MCP for conversational queries.
The ideal setup combines multiple tools: MCP for conversational analytics, Superset for dashboards, and a data consulting partner like D23 to tie it all together.
Building Production-Grade MCP Servers
The examples above are simplified for clarity. A production-grade MCP server needs additional components:
Caching Layer
HubSpot API calls are rate-limited. Implement a caching layer (Redis, in-memory cache, or database) to store frequently requested data. For example, pipeline summaries might be cached for 5 minutes, while individual contact lookups might be cached for 1 hour.
Error Handling and Retries
Network requests fail. Implement exponential backoff for retries, graceful degradation when the HubSpot API is slow, and clear error messages for Claude when data is unavailable.
Monitoring and Observability
Track:
- Request latency (how long does it take to answer a question?)
- Error rates (how often do requests fail?)
- Token usage (how many API calls are we making?)
- Tool usage (which questions are asked most frequently?)
This data helps you optimize your server and understand how your team uses it.
Scalability Considerations
If multiple users are querying your MCP server simultaneously, you need to handle concurrent requests. Consider:
- Connection pooling for HubSpot API calls
- Request queuing to prevent overwhelming the API
- Horizontal scaling (running multiple instances of your server behind a load balancer)
Extending Your MCP Server
Once your basic HubSpot MCP server is live, you can extend it in several directions:
Multi-Source Analytics
Add tools that pull data from other sources—Google Analytics, Mixpanel, your data warehouse—and combine them with HubSpot data. For example, a tool called get_customer_360 could return contact info from HubSpot, engagement metrics from Mixpanel, and revenue data from your data warehouse in a single response.
According to Composio’s guide on HubSpot MCP integration for AI agents, this kind of multi-source integration is increasingly common, with teams building AI agents that synthesize data from dozens of tools.
Predictive Analytics
Integrate machine learning models that predict churn, identify high-value leads, or forecast pipeline. Your MCP server can call these models and return predictions alongside historical data.
Automated Actions
Go beyond read-only analytics. Allow Claude to take actions like creating new deals, updating contact properties, or sending emails. This turns your MCP server from a reporting tool into an automation engine.
Implementing MCP with Your Analytics Stack
If you’re using D23’s managed Apache Superset platform, you can integrate MCP into your broader analytics strategy:
- Set up your MCP server for HubSpot using the patterns described above
- Connect HubSpot to D23 via API to populate dashboards and enable self-serve analytics
- Use D23’s data consulting services to design an analytics architecture that combines conversational (MCP) and dashboard-based (Superset) analytics
- Train your team on when to use conversational queries (ad-hoc questions) vs. dashboards (recurring reporting)
This integrated approach gives you the best of both worlds: fast conversational analytics for immediate questions and polished, self-serve dashboards for team-wide insights.
Getting Started: Next Steps
If you’re ready to build an MCP server for HubSpot, here’s the recommended path:
- Assess your team’s analytics needs: What questions do they ask most frequently? Which of those could be answered by an MCP server?
- Start small: Build 3-5 tools that answer your team’s most common questions. Don’t try to expose all of HubSpot’s data at once.
- Test with Claude: Use Claude’s web interface or API to test your server. Iterate based on feedback.
- Implement security and monitoring: Add authentication, rate limiting, logging, and observability before rolling out to your team.
- Integrate with your existing BI stack: Connect your MCP server to Superset, dashboards, or other analytics tools.
- Measure adoption and impact: Track which questions are asked, how long it takes to get answers, and whether teams are making faster decisions.
For guidance on analytics architecture and best practices, consider working with experts. D23 provides data consulting services specifically designed for teams adopting open-source BI and AI-powered analytics.
Conclusion
The Model Context Protocol represents a fundamental shift in how teams interact with analytics. Instead of navigating dashboards or waiting for analysts to run reports, you can ask Claude natural language questions and get immediate answers from your HubSpot data.
Building an MCP server for HubSpot is straightforward, especially if you follow the patterns outlined above. Start with a few high-value tools, test thoroughly, and expand over time. When combined with managed analytics platforms like D23’s Apache Superset offering, MCP creates a complete analytics experience that scales across your organization.
Your marketing team deserves analytics tools that work at the speed of conversation. MCP makes that possible.