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 };
    });

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observed

TDQS

C2.9/5.0
Behavior2/5

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

Annotations are absent, so the description carries the full burden. It states 'Get activity history', which implies a read-only operation, but does not disclose any behavioral traits such as whether it returns a list or single object, whether it supports filtering, or if any side effects occur. More detail is needed for safe invocation.

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

Conciseness4/5

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

The description is a single sentence with no wasted words. It is front-loaded with the key information. Could be slightly expanded to include more detail while remaining concise, hence 4.

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

Completeness3/5

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

Given the simplicity of the tool (one parameter, no output schema), the description provides the core purpose and required parameter. However, it lacks information about the return format, potential pagination, or examples of activity types. It is adequate but leaves some questions unanswered for an AI agent.

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?

Schema coverage is 100% with a single parameter 'company_id' having a description. The tool description does not add additional semantic value beyond the schema, but the schema itself is sufficient. Baseline 3 is appropriate.

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 verb 'Get' and the resource 'activity history' for a specific company. It distinguishes from sibling tools like hubspot_get_company (which likely returns company details) and hubspot_get_active_companies (list of companies). However, it could specify the type of activity for even greater clarity.

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?

No guidance is provided about when to use this tool versus alternatives such as hubspot_get_company or hubspot_get_recent_conversations. The description lacks context on prerequisites, such as needing a valid company_id, or when to prefer this over other activity-related tools.

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