Skip to main content
Glama
kesslerio

Attio MCP Server

by kesslerio

search-records

Read-onlyIdempotent

Search across companies, people, records, tasks, deals, notes and lists in Attio CRM using queries, filters, date ranges and sorting options to find specific information.

Instructions

Universal search across all resource types (companies, people, records, tasks)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
created_afterNoFilter records created after this date (ISO 8601)
created_beforeNoFilter records created before this date (ISO 8601)
date_fieldNoWhich date field to filter oncreated_at
date_fromNoStart date for filtering (ISO 8601 format)
date_toNoEnd date for filtering (ISO 8601 format)
fieldsNoFields to search (content)
filtersNoAdvanced filter conditions
limitNoMaximum number of results to return
match_typeNoString matching
offsetNoNumber of results to skip for pagination
queryNoSearch query string
resource_typeYesType of resource to operate on (companies, people, lists, records, tasks)
search_typeNoType of search
sortNoSort order
timeframeNoRelative timeframe filter
updated_afterNoFilter records updated after this date (ISO 8601)
updated_beforeNoFilter records updated before this date (ISO 8601)

Implementation Reference

  • Deprecated tool alias that maps user-called 'search-records' to canonical 'records_search' tool
    'search-records': {
      target: 'records_search',
      reason: 'Phase 1 search tool rename (#776)',
      since: SINCE_PHASE_1,
      removal: 'v1.x (TBD)',
    },
  • Registers 'records_search' tool configuration as part of core universal operations
      records_search: searchRecordsConfig,
      records_get_details: getRecordDetailsConfig,
      'create-record': createRecordConfig,
      'update-record': updateRecordConfig,
      'delete-record': deleteRecordConfig,
      records_get_attributes: getAttributesConfig,
      records_discover_attributes: discoverAttributesConfig,
      records_get_info: getDetailedInfoConfig,
    };
  • MCP tool definition including input schema (searchRecordsSchema) and description for 'records_search'
    export const searchRecordsDefinition = {
      name: 'records_search',
      description: formatToolDescription({
        capability: 'Search across companies, people, deals, tasks, and records',
        boundaries: 'create or modify records',
        constraints: 'Returns max 100 results (default: 10)',
        recoveryHint: 'use records.discover_attributes to find searchable fields',
      }),
      inputSchema: searchRecordsSchema,
      annotations: {
        readOnlyHint: true,
        idempotentHint: true,
      },
    };
  • MCP tool handler configuration for 'records_search': validates params, calls handleUniversalSearch (delegates to UniversalSearchService), handles errors and formats results
    export const searchRecordsConfig: UniversalToolConfig<
      UniversalSearchParams,
      AttioRecord[]
    > = {
      name: 'records_search',
      handler: async (params: UniversalSearchParams): Promise<AttioRecord[]> => {
        try {
          const sanitizedParams = validateUniversalToolParams(
            'records_search',
            params
          );
          return await handleUniversalSearch(sanitizedParams);
        } catch (error: unknown) {
          return await handleSearchError(
            error,
            params.resource_type,
            params as unknown as Record<string, unknown>
          );
        }
      },
      formatResult: (
        results: AttioRecord[] | { data: AttioRecord[] },
        ...args: unknown[]
      ): string => {
        const resourceType = args[0] as UniversalResourceType | undefined;
        if (!results) {
          const typeName = resourceType
            ? getPluralResourceType(resourceType)
            : 'records';
          return `Found 0 ${typeName}`;
        }
    
        const recordsArray = Array.isArray(results)
          ? results
          : (results?.data ?? []);
    
        if (!Array.isArray(recordsArray) || recordsArray.length === 0) {
          const typeName = resourceType
            ? getPluralResourceType(resourceType)
            : 'records';
          return `Found 0 ${typeName}`;
        }
    
        const typeName = resourceType
          ? getPluralResourceType(resourceType)
          : 'records';
    
        const formattedResults = recordsArray
          .map((record, index) => {
            let identifier = 'Unnamed';
            let id = String(record.id?.record_id || 'unknown');
    
            const values = record.values || {};
            const getFirstValue = (field: unknown): string | undefined => {
              if (!field || !Array.isArray(field) || field.length === 0)
                return undefined;
              const firstItem = field[0] as { value?: string };
              return firstItem &&
                typeof firstItem === 'object' &&
                firstItem !== null &&
                'value' in firstItem
                ? String(firstItem.value)
                : undefined;
            };
    
            if (resourceType === UniversalResourceType.TASKS) {
              identifier =
                typeof values.content === 'string'
                  ? values.content
                  : getFirstValue(values.content) || 'Unnamed';
              id = String(record.id?.task_id || record.id?.record_id || 'unknown');
            } else if (resourceType === UniversalResourceType.PEOPLE) {
              const valuesAny = values as Record<string, unknown>;
              const name =
                (valuesAny?.name as { full_name?: string }[] | undefined)?.[0]
                  ?.full_name ||
                (valuesAny?.name as { value?: string }[] | undefined)?.[0]?.value ||
                (valuesAny?.name as { formatted?: string }[] | undefined)?.[0]
                  ?.formatted ||
                (valuesAny?.full_name as { value?: string }[] | undefined)?.[0]
                  ?.value ||
                getFirstValue(values.name) ||
                'Unnamed';
    
              const emailValue =
                (
                  valuesAny?.email_addresses as
                    | { email_address?: string }[]
                    | undefined
                )?.[0]?.email_address ||
                (
                  valuesAny?.email_addresses as { value?: string }[] | undefined
                )?.[0]?.value ||
                getFirstValue(values.email) ||
                getFirstValue(valuesAny.email_addresses);
    
              identifier = emailValue ? `${name} (${emailValue})` : name;
            } else if (resourceType === UniversalResourceType.COMPANIES) {
              const name =
                typeof values.name === 'string'
                  ? values.name
                  : getFirstValue(values.name) || 'Unnamed';
              const website = getFirstValue(values.website);
              const domain =
                values.domains &&
                Array.isArray(values.domains) &&
                values.domains.length > 0
                  ? (values.domains[0] as { domain?: string }).domain
                  : undefined;
              const email = getFirstValue(values.email);
              const contactInfo = website || domain || email;
              identifier = contactInfo ? `${name} (${contactInfo})` : name;
            } else {
              const nameValue = getFirstValue(values.name);
              const titleValue = getFirstValue(values.title);
              identifier = nameValue || titleValue || 'Unnamed';
            }
    
            return `${index + 1}. ${identifier} (ID: ${id})`;
          })
          .join('\n');
    
        return `Found ${recordsArray.length} ${typeName}:\n${formattedResults}`;
      },
      structuredOutput: (
        results: AttioRecord[] | { data: AttioRecord[] }
      ): Record<string, unknown> => {
        // Return the raw records array for JSON parsing
        const recordsArray = Array.isArray(results)
          ? results
          : (results?.data ?? []);
        return { data: recordsArray, count: recordsArray.length };
      },
    };
  • Core search implementation: handles validation, performance tracking, timeframe processing, and delegates to resource-specific strategies or Query API via performSearchByResourceType
    static async searchRecords(
      params: UniversalSearchParams
    ): Promise<AttioRecord[]> {
      const {
        resource_type,
        query,
        filters,
        limit,
        offset,
        search_type = SearchType.BASIC,
        fields,
        match_type = MatchType.PARTIAL,
        sort = SortType.NAME,
        // New TC search parameters
        relationship_target_type,
        relationship_target_id,
        timeframe_attribute,
        start_date,
        end_date,
        date_operator,
        content_fields,
        use_or_logic,
        // Issue #475: New date filtering parameters
        date_from,
        date_to,
        created_after,
        created_before,
        updated_after,
        updated_before,
        timeframe,
        date_field,
      } = params;
    
      // Start performance tracking
      const perfId = enhancedPerformanceTracker.startOperation(
        'search-records',
        'search',
        {
          resourceType: resource_type,
          hasQuery: !!query,
          hasFilters: !!(filters && Object.keys(filters).length > 0),
          limit,
          offset,
          searchType: search_type,
          hasFields: !!(fields && fields.length > 0),
          matchType: match_type,
          sortType: sort,
        }
      );
    
      // Track validation timing
      const validationStart = performance.now();
    
      // Validate pagination parameters using ValidationService
      ValidationService.validatePaginationParameters({ limit, offset }, perfId);
    
      // Validate filter schema for malformed advanced filters
      ValidationService.validateFiltersSchema(filters);
    
      enhancedPerformanceTracker.markTiming(
        perfId,
        'validation',
        performance.now() - validationStart
      );
    
      // Issue #475: Convert user-friendly date parameters to API format
      let processedTimeframeParams = {
        timeframe_attribute,
        start_date,
        end_date,
        date_operator,
      };
    
      try {
        const dateConversion = convertDateParamsToTimeframeQuery({
          date_from,
          date_to,
          created_after,
          created_before,
          updated_after,
          updated_before,
          timeframe,
          date_field,
        });
    
        if (dateConversion) {
          // Use converted parameters, prioritizing user-friendly parameters
          processedTimeframeParams = {
            ...processedTimeframeParams,
            ...dateConversion,
          };
        }
      } catch (dateError: unknown) {
        // Re-throw date validation errors with helpful context
        const errorMessage =
          dateError instanceof Error
            ? `Date parameter validation failed: ${dateError.message}`
            : 'Invalid date parameters provided';
        throw new Error(errorMessage);
      }
    
      // Auto-detect timeframe searches and FORCE them to use the Query API
      let finalSearchType = search_type;
      const hasTimeframeParams =
        processedTimeframeParams.timeframe_attribute &&
        (processedTimeframeParams.start_date ||
          processedTimeframeParams.end_date);
    
      if (hasTimeframeParams) {
        finalSearchType = SearchType.TIMEFRAME;
        debug(
          'UniversalSearchService',
          'FORCING timeframe search to use Query API (advanced search API does not support date comparisons)',
          {
            originalSearchType: search_type,
            timeframe_attribute: processedTimeframeParams.timeframe_attribute,
            start_date: processedTimeframeParams.start_date,
            end_date: processedTimeframeParams.end_date,
            date_operator: processedTimeframeParams.date_operator,
          }
        );
      }
    
      // Track API call timing
      const apiStart = enhancedPerformanceTracker.markApiStart(perfId);
      let results: AttioRecord[];
    
      try {
        results = await this.performSearchByResourceType(
          resource_type,
          {
            query,
            filters,
            limit,
            offset,
            search_type: finalSearchType,
            fields,
            match_type,
            sort,
            // New TC search parameters
            relationship_target_type,
            relationship_target_id,
            // Use processed timeframe parameters (Issue #475)
            timeframe_attribute: processedTimeframeParams.timeframe_attribute,
            start_date: processedTimeframeParams.start_date,
            end_date: processedTimeframeParams.end_date,
            date_operator: processedTimeframeParams.date_operator,
            content_fields,
            use_or_logic,
          },
          perfId,
          apiStart
        );
    
        enhancedPerformanceTracker.markApiEnd(perfId, apiStart);
        enhancedPerformanceTracker.endOperation(perfId, true, undefined, 200, {
          recordCount: results.length,
        });
    
        return results;
      } catch (apiError: unknown) {
        enhancedPerformanceTracker.markApiEnd(perfId, apiStart);
    
        const errorObj = apiError as Record<string, unknown>;
        const statusCode =
          ((errorObj?.response as Record<string, unknown>)?.status as number) ||
          (errorObj?.statusCode as number) ||
          500;
        const errorMessage =
          apiError instanceof Error ? apiError.message : 'Search failed';
        enhancedPerformanceTracker.endOperation(
          perfId,
          false,
          errorMessage,
          statusCode
        );
        throw apiError;
      }
    }
Behavior3/5

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

Annotations declare readOnlyHint=true and idempotentHint=true, indicating this is a safe, repeatable read operation. The description adds no behavioral context beyond what annotations provide—it doesn't mention pagination behavior, rate limits, authentication requirements, or what happens with empty results. However, it doesn't contradict the annotations either.

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 immediately conveys the core functionality without any wasted words. It's appropriately sized and front-loaded with the essential information about what the tool does.

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?

For a complex search tool with 17 parameters, 100% schema coverage, and read-only/idempotent annotations, the description is minimally adequate. It states the purpose but lacks guidance on usage versus siblings, behavioral details, or output format (no output schema exists). The annotations provide safety context, but the description doesn't add enough value beyond the structured data.

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 description coverage is 100%, with all 17 parameters well-documented in the schema itself. The description adds no parameter-specific information beyond the general scope ('across all resource types'), which is already covered by the 'resource_type' parameter's enum. The baseline score of 3 is appropriate when the schema does all 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 tool's purpose: 'Universal search across all resource types (companies, people, records, tasks)'. It specifies the verb ('search') and scope ('universal across all resource types'), but doesn't explicitly distinguish it from sibling tools like 'search', 'search-by-content', 'search-by-timeframe', or 'advanced-search', which appear to offer similar functionality.

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. With multiple sibling search tools (e.g., 'search', 'search-by-content', 'search-by-timeframe', 'advanced-search'), the description fails to explain what makes this 'universal search' different or when it should be preferred over other search options.

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/kesslerio/attio-mcp-server'

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