Skip to main content
Glama
MakingChatbots

Genesys Cloud MCP Server

conversation_topics

Retrieves business-level intents like cancellation or billing detected from speech and text analytics for a specific conversation.

Instructions

Retrieves Speech and Text Analytics topics detected for a specific conversation. Topics represent business-level intents (e.g. cancellation, billing enquiry) inferred from recognised phrases in the customer-agent interaction.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
conversationIdYesA UUID for a conversation. (e.g., 00000000-0000-0000-0000-000000000000)

Implementation Reference

  • The main handler function for the conversation_topics tool. It receives a conversationId, fetches conversation details via analyticsApi, queries transcript aggregates to find topic IDs, then retrieves topic names from speechTextAnalyticsApi, returning them as JSON.
    export const conversationTopics: ToolFactory<
      ToolDependencies,
      typeof paramsSchema
    > = ({ speechTextAnalyticsApi, analyticsApi }) =>
      createTool({
        schema: {
          name: "conversation_topics",
          annotations: { title: "Conversation Topics" },
          description:
            "Retrieves Speech and Text Analytics topics detected for a specific conversation. Topics represent business-level intents (e.g. cancellation, billing enquiry) inferred from recognised phrases in the customer-agent interaction.",
          paramsSchema,
        },
        call: async ({ conversationId }) => {
          let conversationDetails: Models.AnalyticsConversationWithoutAttributes;
    
          try {
            conversationDetails =
              await analyticsApi.getAnalyticsConversationDetails(conversationId);
          } catch (error: unknown) {
            const errorMessage = isUnauthorisedError(error)
              ? "Failed to retrieve conversation topics: Unauthorised access. Please check API credentials or permissions"
              : `Failed to retrieve conversation topics: ${error instanceof Error ? error.message : JSON.stringify(error)}`;
    
            return errorResult(errorMessage);
          }
    
          if (
            !conversationDetails.conversationStart ||
            !conversationDetails.conversationEnd
          ) {
            return errorResult(
              "Unable to find conversation Start and End date needed for retrieving topics",
            );
          }
    
          // Widen the time range either side to ensure the conversation timeframe is enclosed.
          // Conversation not returned if either only partially covered by interval, or matched exactly.
          const startDate = new Date(conversationDetails.conversationStart);
          startDate.setMinutes(startDate.getMinutes() - 10);
    
          const endDate = new Date(conversationDetails.conversationEnd);
          endDate.setMinutes(endDate.getMinutes() + 10);
    
          let jobDetails: Models.TranscriptAggregateQueryResponse;
          try {
            jobDetails = await analyticsApi.postAnalyticsTranscriptsAggregatesQuery(
              {
                interval: `${startDate.toISOString()}/${endDate.toISOString()}`,
                filter: {
                  type: "and",
                  predicates: [
                    {
                      dimension: "conversationId",
                      value: conversationId,
                    },
                    {
                      dimension: "resultsBy",
                      value: "communication",
                    },
                  ],
                },
                groupBy: ["topicId"],
                metrics: ["nTopicCommunications"],
              },
            );
          } catch (error: unknown) {
            const errorMessage = isUnauthorisedError(error)
              ? "Failed to retrieve conversation topics: Unauthorised access. Please check API credentials or permissions"
              : `Failed to retrieve conversation topics: ${error instanceof Error ? error.message : JSON.stringify(error)}`;
    
            return errorResult(errorMessage);
          }
    
          const topicIds = new Set<string>();
    
          for (const result of jobDetails.results ?? []) {
            if (result.group?.topicId) {
              topicIds.add(result.group.topicId);
            }
          }
    
          if (topicIds.size === 0) {
            return {
              content: [
                {
                  type: "text",
                  text: `Conversation ID: ${conversationId}\nNo detected topics for this conversation.`,
                },
              ],
            };
          }
    
          const topics: Models.ListedTopic[] = [];
    
          try {
            for (const topicIdChunk of chunks(
              Array.from(topicIds.values()),
              MAX_IDS_ALLOWED_BY_API,
            )) {
              const topicsListings =
                await speechTextAnalyticsApi.getSpeechandtextanalyticsTopics({
                  ids: topicIdChunk,
                  pageSize: MAX_IDS_ALLOWED_BY_API,
                });
    
              topics.push(...(topicsListings.entities ?? []));
            }
          } catch (error: unknown) {
            const errorMessage = isUnauthorisedError(error)
              ? "Failed to retrieve conversation topics: Unauthorised access. Please check API credentials or permissions"
              : `Failed to retrieve conversation topics: ${error instanceof Error ? error.message : JSON.stringify(error)}`;
    
            return errorResult(errorMessage);
          }
    
          const topicNames = topics
            .filter((topic) => topic.name && topic.description)
            .map(({ name, description }) => ({
              name: name ?? "",
              description: description ?? "",
            }));
    
          return {
            content: [
              {
                type: "text",
                text: JSON.stringify({
                  conversationId: conversationId,
                  detectedTopics: topicNames,
                }),
              },
            ],
          };
        },
      });
  • Zod schema for input validation: requires a single 'conversationId' parameter as a UUID string.
    const paramsSchema = z.object({
      conversationId: z
        .string()
        .uuid()
        .describe(
          "A UUID for a conversation. (e.g., 00000000-0000-0000-0000-000000000000)",
        ),
    });
  • src/index.ts:107-119 (registration)
    Registration of the conversation_topics tool on the MCP server. Creates the tool with dependencies (speechTextAnalyticsApi, analyticsApi), registers it by name, and wraps the call with OAuth authentication.
    const conversationTopicsTool = conversationTopics({
      speechTextAnalyticsApi,
      analyticsApi,
    });
    server.registerTool(
      conversationTopicsTool.schema.name,
      {
        description: conversationTopicsTool.schema.description,
        inputSchema: conversationTopicsTool.schema.paramsSchema.shape,
        annotations: conversationTopicsTool.schema.annotations,
      },
      withAuth(conversationTopicsTool.call),
    );
  • Generator function that splits an array into chunks of a specified size, used to batch topic ID requests respecting the API limit of 50 IDs per call.
    export function* chunks<T>(arr: T[], n: number): Generator<T[], void> {
      if (!Number.isInteger(n) || n <= 0) {
        throw new Error("Chunk size must be a positive integer");
      }
    
      for (let i = 0; i < arr.length; i += n) {
        yield arr.slice(i, i + n);
      }
    }

Schema Changelog

Changes observed during successful MCP inspections.

  1. Changed2 schema fields changedv1.0.4
    • removedInput schema / additionalProperties
      Removed value: -false
    • addedInput schema / properties / conversationId / pattern
      Added value: +"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
  2. First observedv1.0.0

TDQS

A3.6/5.0
Behavior3/5

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

The description conveys that the operation is a retrieval ('Retrieves') and adds context about how topics are derived ('inferred from recognised phrases in the customer-agent interaction'). With no readOnlyHint or destructiveHint annotations, the description carries the burden, and it partially covers safety and semantics. It does not disclose output shape, empty-result behavior, pagination, or any authentication/data-availability constraints.

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?

Two sentences with no unnecessary wording. The first sentence front-loads the action and object, and the second sentence adds useful semantic context about what topics represent. Every phrase earns its place.

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

Completeness4/5

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

This is a simple single-parameter retrieval tool, and the description clearly identifies the returned concept (topics) and its meaning. The absence of an output schema is a minor gap because the exact response structure is not described, but for the tool's simplicity the definition is largely complete.

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 already fully documents the single parameter, conversationId, including its type, format, pattern, and an example. The description adds only the contextual notion of 'a specific conversation', which does not materially expand on the schema. Given 100% schema description coverage, the baseline of 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 states a specific action and resource: 'Retrieves Speech and Text Analytics topics detected for a specific conversation.' It also clarifies what 'topics' mean with examples like cancellation and billing enquiry. However, it does not explicitly differentiate itself from sibling per-conversation tools such as conversation_sentiment or conversation_transcript.

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

Usage Guidelines3/5

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

Usage is implied: an agent can infer this tool is appropriate when it has a specific conversationId and needs business-level topics for that conversation. However, there is no explicit when-to-use guidance, no mention of alternatives, and no exclusions to prevent choosing this tool over the sibling tools.

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