Skip to main content
Glama
lkm1developer

HubSpot MCP Server

hubspot_get_company_activity

Retrieve activity history for a HubSpot company by providing its company ID to track interactions and engagements.

Instructions

Get activity history for a specific company

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
company_idYesHubSpot company ID

Implementation Reference

  • Core handler implementing hubspot_get_company_activity: fetches company engagements via associations API, retrieves details for each, formats by type (NOTE, EMAIL, TASK, MEETING, CALL), and converts datetimes.
    async getCompanyActivity(companyId: string): Promise<any> {
      try {
        // Step 1: Get all engagement IDs associated with the company using CRM Associations v4 API
        const associatedEngagements = await this.client.crm.associations.v4.basicApi.getPage(
          'companies',
          companyId,
          'engagements',
          undefined,
          500
        );
        
        // Extract engagement IDs from the associations response
        const engagementIds: string[] = [];
        if (associatedEngagements.results) {
          for (const result of associatedEngagements.results) {
            engagementIds.push(result.toObjectId);
          }
        }
        
        // Step 2: Get detailed information for each engagement
        const activities = [];
        for (const engagementId of engagementIds) {
          const engagementResponse = await this.client.apiRequest({
            method: 'GET',
            path: `/engagements/v1/engagements/${engagementId}`
          });
          
          // Ensure we have a proper response body
          const responseBody = engagementResponse.body as any;
          const engagementData = responseBody.engagement || {};
          const metadata = responseBody.metadata || {};
          
          // Format the engagement
          const formattedEngagement: Record<string, any> = {
            id: engagementData.id,
            type: engagementData.type,
            created_at: engagementData.createdAt,
            last_updated: engagementData.lastUpdated,
            created_by: engagementData.createdBy,
            modified_by: engagementData.modifiedBy,
            timestamp: engagementData.timestamp,
            associations: (engagementResponse.body as any).associations || {}
          };
          
          // Add type-specific metadata formatting
          if (engagementData.type === 'NOTE') {
            formattedEngagement.content = metadata.body || '';
          } else if (engagementData.type === 'EMAIL') {
            formattedEngagement.content = {
              subject: metadata.subject || '',
              from: {
                raw: metadata.from?.raw || '',
                email: metadata.from?.email || '',
                firstName: metadata.from?.firstName || '',
                lastName: metadata.from?.lastName || ''
              },
              to: (metadata.to || []).map((recipient: any) => ({
                raw: recipient.raw || '',
                email: recipient.email || '',
                firstName: recipient.firstName || '',
                lastName: recipient.lastName || ''
              })),
              cc: (metadata.cc || []).map((recipient: any) => ({
                raw: recipient.raw || '',
                email: recipient.email || '',
                firstName: recipient.firstName || '',
                lastName: recipient.lastName || ''
              })),
              bcc: (metadata.bcc || []).map((recipient: any) => ({
                raw: recipient.raw || '',
                email: recipient.email || '',
                firstName: recipient.firstName || '',
                lastName: recipient.lastName || ''
              })),
              sender: {
                email: metadata.sender?.email || ''
              },
              body: metadata.text || metadata.html || ''
            };
          } else if (engagementData.type === 'TASK') {
            formattedEngagement.content = {
              subject: metadata.subject || '',
              body: metadata.body || '',
              status: metadata.status || '',
              for_object_type: metadata.forObjectType || ''
            };
          } else if (engagementData.type === 'MEETING') {
            formattedEngagement.content = {
              title: metadata.title || '',
              body: metadata.body || '',
              start_time: metadata.startTime,
              end_time: metadata.endTime,
              internal_notes: metadata.internalMeetingNotes || ''
            };
          } else if (engagementData.type === 'CALL') {
            formattedEngagement.content = {
              body: metadata.body || '',
              from_number: metadata.fromNumber || '',
              to_number: metadata.toNumber || '',
              duration_ms: metadata.durationMilliseconds,
              status: metadata.status || '',
              disposition: metadata.disposition || ''
            };
          }
          
          activities.push(formattedEngagement);
        }
        
        // Convert any datetime fields and return
        return convertDatetimeFields(activities);
      } catch (error: any) {
        console.error('Error getting company activity:', error);
        return { error: error.message };
      }
    }
  • Input schema definition for the tool, specifying required company_id parameter.
      name: 'hubspot_get_company_activity',
      description: 'Get activity history for a specific company',
      inputSchema: {
        type: 'object',
        properties: {
          company_id: { 
            type: 'string', 
            description: 'HubSpot company ID' 
          }
        },
        required: ['company_id']
      }
    },
  • MCP tool dispatch handler: extracts company_id argument and delegates to HubSpotClient.getCompanyActivity, returns JSON-formatted result.
    case 'hubspot_get_company_activity': {
      const result = await this.hubspot.getCompanyActivity(args.company_id as string);
      return {
        content: [{
          type: 'text',
          text: JSON.stringify(result, null, 2)
        }]
      };
    }
  • Recursive utility to convert Date objects to ISO strings in response objects, used in getCompanyActivity.
    export function convertDatetimeFields(obj: any): any {
      if (obj === null || obj === undefined) {
        return obj;
      }
      
      if (typeof obj === 'object') {
        if (obj instanceof Date) {
          return obj.toISOString();
        }
        
        if (Array.isArray(obj)) {
          return obj.map(item => convertDatetimeFields(item));
        }
        
        const result: Record<string, any> = {};
        for (const [key, value] of Object.entries(obj)) {
          result[key] = convertDatetimeFields(value);
        }
        return result;
      }
      
      return obj;
    }
  • src/index.ts:76-227 (registration)
    Registers the tool by including it in the list returned by ListToolsRequest handler.
    this.server.setRequestHandler(ListToolsRequestSchema, async () => {
      // Define available tools
      const tools: Tool[] = [
        {
          name: 'hubspot_create_contact',
          description: 'Create a new contact in HubSpot',
          inputSchema: {
            type: 'object',
            properties: {
              firstname: { 
                type: 'string', 
                description: "Contact's first name" 
              },
              lastname: { 
                type: 'string', 
                description: "Contact's last name" 
              },
              email: { 
                type: 'string', 
                description: "Contact's email address" 
              },
              properties: { 
                type: 'object', 
                description: 'Additional contact properties',
                additionalProperties: true
              }
            },
            required: ['firstname', 'lastname']
          }
        },
        {
          name: 'hubspot_create_company',
          description: 'Create a new company in HubSpot',
          inputSchema: {
            type: 'object',
            properties: {
              name: { 
                type: 'string', 
                description: 'Company name' 
              },
              properties: { 
                type: 'object', 
                description: 'Additional company properties',
                additionalProperties: true
              }
            },
            required: ['name']
          }
        },
        {
          name: 'hubspot_get_company_activity',
          description: 'Get activity history for a specific company',
          inputSchema: {
            type: 'object',
            properties: {
              company_id: { 
                type: 'string', 
                description: 'HubSpot company ID' 
              }
            },
            required: ['company_id']
          }
        },
        {
          name: 'hubspot_get_recent_engagements',
          description: 'Get recent engagement activities across all contacts and companies',
          inputSchema: {
            type: 'object',
            properties: {
              days: { 
                type: 'number', 
                description: 'Number of days to look back (default: 7)',
                default: 7
              },
              limit: { 
                type: 'number', 
                description: 'Maximum number of engagements to return (default: 50)',
                default: 50
              }
            }
          }
        },
        {
          name: 'hubspot_get_active_companies',
          description: 'Get most recently active companies from HubSpot',
          inputSchema: {
            type: 'object',
            properties: {
              limit: { 
                type: 'number', 
                description: 'Maximum number of companies to return (default: 10)',
                default: 10
              }
            }
          }
        },
        {
          name: 'hubspot_get_active_contacts',
          description: 'Get most recently active contacts from HubSpot',
          inputSchema: {
            type: 'object',
            properties: {
              limit: { 
                type: 'number', 
                description: 'Maximum number of contacts to return (default: 10)',
                default: 10
              }
            }
          }
        },
        {
          name: 'hubspot_update_contact',
          description: 'Update an existing contact in HubSpot (ignores if contact does not exist)',
          inputSchema: {
            type: 'object',
            properties: {
              contact_id: { 
                type: 'string', 
                description: 'HubSpot contact ID to update' 
              },
              properties: { 
                type: 'object', 
                description: 'Contact properties to update',
                additionalProperties: true
              }
            },
            required: ['contact_id', 'properties']
          }
        },
        {
          name: 'hubspot_update_company',
          description: 'Update an existing company in HubSpot (ignores if company does not exist)',
          inputSchema: {
            type: 'object',
            properties: {
              company_id: { 
                type: 'string', 
                description: 'HubSpot company ID to update' 
              },
              properties: { 
                type: 'object', 
                description: 'Company properties to update',
                additionalProperties: true
              }
            },
            required: ['company_id', 'properties']
          }
        }
      ];
      
      return { tools };
    });

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/lkm1developer/hubspot-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server