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'],
    },
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It states the tool sends a message but doesn't describe what happens after sending (e.g., whether it triggers agent processing, returns a response, or creates side effects). It mentions conversation continuation via conversationId but doesn't explain behavioral implications of using this parameter.

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 with zero wasted words. It's appropriately sized for a simple messaging tool and front-loads the core functionality.

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?

For a messaging tool with no annotations and no output schema, the description is insufficient. It doesn't explain what happens after message sending (response format, agent processing behavior), nor does it provide context about conversation lifecycle or relationships with sibling tools. The agent would need to guess about important behavioral aspects.

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%, so the schema already documents both parameters thoroughly. The description doesn't add any meaning beyond what the schema provides about message content or conversation continuation. Baseline 3 is appropriate when 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 ('Send a message') and target ('to the Copilot Studio Agent'), providing a specific verb+resource combination. However, it doesn't differentiate this tool from its siblings (end_conversation, get_conversation_history, start_conversation) which all operate on conversations with the same agent.

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. The description doesn't mention prerequisites (e.g., whether a conversation must be started first), nor does it explain the relationship with sibling tools like start_conversation or end_conversation.

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/bradcstevens/copilot-studio-agent-direct-line-mcp'

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