Skip to main content
Glama
bradcstevens

Copilot Studio Agent Direct Line MCP Server

by bradcstevens

send_message

Send messages to Microsoft Copilot Studio Agents via Direct Line API to interact with custom conversational agents directly from development environments.

Instructions

Send a message to the Copilot Studio Agent

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
messageYesThe message text to send
conversationIdNoOptional conversation ID to continue existing conversation

Implementation Reference

  • The core handler function that executes the send_message tool logic: validates input using SendMessageArgsSchema, manages or creates conversations, sends the message via DirectLineClient, polls for the bot's response, logs audit, and returns conversationId, response, and activityId.
    private async handleSendMessage(args: Record<string, unknown>, userContext?: UserContext) {
      const { message, conversationId } = validateToolArgs(SendMessageArgsSchema, args);
    
      // Validate permissions if user context exists
      if (userContext && conversationId) {
        this.validateUserConversationAccess(userContext.userId, conversationId);
      }
    
      try {
        let convId = conversationId;
        let convState;
    
        // Get or create conversation
        if (convId) {
          convState = this.conversationManager.getConversation(convId);
          if (!convState) {
            throw new Error(`Conversation ${convId} not found or expired`);
          }
        } else {
          // Create new conversation with user-specific client ID
          const clientId = userContext
            ? `user-${userContext.userId}-${Date.now()}`
            : `mcp-client-${Date.now()}`;
          convState = await this.conversationManager.createConversation(clientId);
          convId = convState.conversationId;
    
          // Associate conversation with user
          if (userContext) {
            this.associateConversationWithUser(userContext.userId, convId);
          }
        }
    
        // Send message to Direct Line with user metadata
        const activityId = await this.client.sendActivity(
          {
            conversationId: convId,
            activity: {
              type: 'message',
              from: {
                id: convState.clientId,
                name: userContext?.name || 'MCP User',
              },
              text: message,
              timestamp: new Date().toISOString(),
              // Add user metadata to activity
              channelData: userContext
                ? {
                    userId: userContext.userId,
                    userEmail: userContext.email,
                    tenantId: userContext.tenantId,
                  }
                : undefined,
            },
          },
          convState.token
        );
    
        // Poll for response
        const startTime = Date.now();
        const timeout = 30000;
        let botResponse = '';
    
        while (Date.now() - startTime < timeout) {
          await new Promise((resolve) => setTimeout(resolve, 1000));
    
          const activitySet = await this.client.getActivities(
            {
              conversationId: convId,
              watermark: convState.watermark,
            },
            convState.token
          );
    
          if (activitySet.watermark) {
            this.conversationManager.updateWatermark(convId, activitySet.watermark);
          }
    
          const botActivities = activitySet.activities.filter(
            (a) => a.type === 'message' && a.from?.id !== convState.clientId
          );
    
          if (botActivities.length > 0) {
            botActivities.forEach((activity) => {
              this.conversationManager.addToHistory(convId!, activity);
            });
    
            const latestBot = botActivities[botActivities.length - 1];
            botResponse = latestBot.text || '[No text response]';
            break;
          }
        }
    
        if (!botResponse) {
          botResponse = '[No response received within timeout period]';
        }
    
        // Audit log
        this.logAudit({
          timestamp: Date.now(),
          userId: userContext?.userId,
          action: 'send_message',
          conversationId: convId,
          details: { activityId },
        });
    
        return createSuccessResponse({
          conversationId: convId,
          response: botResponse,
          activityId,
        });
      } catch (error) {
        throw new Error(
          `Failed to send message: ${error instanceof Error ? error.message : String(error)}`
        );
      }
    }
  • Zod schema for validating send_message tool arguments: requires 'message' string (non-empty), optional 'conversationId' string. Used in handleSendMessage via validateToolArgs.
     * Schema for send_message tool arguments
     */
    export const SendMessageArgsSchema = z.object({
      message: z.string().min(1, 'Message cannot be empty'),
      conversationId: z.string().optional(),
    });
    
    export type SendMessageArgs = z.infer<typeof SendMessageArgsSchema>;
  • Tool registration in the MCP server's ListToolsRequestSchema handler, defining name, description, and inputSchema for send_message.
    {
      name: 'send_message',
      description: 'Send a message to the Copilot Studio Agent',
      inputSchema: {
        type: 'object',
        properties: {
          message: {
            type: 'string',
            description: 'The message text to send',
          },
          conversationId: {
            type: 'string',
            description: 'Optional conversation ID to continue existing conversation',
          },
        },
        required: ['message'],
      },
    },
  • Dispatch/registration in CallToolRequestSchema handler: routes 'send_message' calls to handleSendMessage function.
    switch (name) {
      case 'send_message':
        return await this.handleSendMessage(args || {}, userContext);
  • Duplicate tool registration for HTTP transport mode in handleHttpMessage 'tools/list' case.
    name: 'send_message',
    description: 'Send a message to the Copilot Studio Agent',
    inputSchema: {
      type: 'object',
      properties: {
        message: {
          type: 'string',
          description: 'The message text to send',
        },
        conversationId: {
          type: 'string',
          description: 'Optional conversation ID to continue existing conversation',
        },
      },
      required: ['message'],
    },

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?

With no annotations, the description carries the full burden of behavioral disclosure. It only states the basic action and omits important behaviors such as whether the tool can start a conversation without a conversationId, how it handles invalid conversation IDs, or any side effects. This is a significant gap for a messaging tool.

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 sentence that directly states the tool's purpose with no superfluous words. It is compact and front-loaded, making the core function immediately clear.

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?

Despite the tool's technical simplicity, the description lacks critical context about the conversation lifecycle. The existence of sibling tools (start_conversation, end_conversation) implies a workflow, but the description does not clarify whether send_message requires an existing conversation or can initiate one. This ambiguity affects correct usage.

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 input schema already provides full descriptions for both parameters (message and conversationId). The tool description adds no additional semantics beyond the schema, so the baseline score 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 clearly states the action ('Send') and the object/resource ('a message to the Copilot Studio Agent'). It is distinguishable from siblings like start_conversation and get_conversation_history, though it could be more explicit about whether it sends within an existing conversation or starts a new one.

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 on when to use this tool versus the siblings. There is no mention of prerequisites (e.g., needing an active conversation) or alternatives, leaving the agent to infer the intended workflow.

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