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 };
    });
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It states it's a 'Get' operation, implying read-only behavior, but doesn't clarify permissions, rate limits, pagination, error handling, or what 'activity history' entails (e.g., types of activities, date ranges). This leaves significant gaps for a tool with potential complexity.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that directly states the tool's purpose without unnecessary words. It's front-loaded and appropriately sized for a simple tool, with every word contributing to clarity.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the lack of annotations and output schema, the description is incomplete. It doesn't explain what 'activity history' includes (e.g., engagement types, timestamps), return format, or error scenarios. For a tool that could involve complex data retrieval, this leaves the agent under-informed.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema description coverage is 100%, with the single parameter 'company_id' well-documented in the schema as 'HubSpot company ID'. The description doesn't add any parameter-specific details beyond implying the tool acts on a company, so it meets the baseline of 3 where the schema does the heavy lifting.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('Get activity history') and target resource ('for a specific company'), providing a specific verb+resource combination. However, it doesn't differentiate from sibling tools like 'hubspot_get_recent_engagements' which might also retrieve activity-related data, keeping it from a perfect score.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention prerequisites (e.g., needing a valid company ID), exclusions, or comparisons to siblings like 'hubspot_get_active_companies' or 'hubspot_get_recent_engagements', leaving the agent with minimal context for selection.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other 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