Skip to main content
Glama
bradcstevens

Copilot Studio Agent Direct Line MCP Server

by bradcstevens

start_conversation

Initiate a new conversation with a Microsoft Copilot Studio Agent to interact with custom AI assistants through Direct Line 3.0 API integration.

Instructions

Start a new conversation with the Copilot Studio Agent

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
initialMessageNoOptional first message to send

Implementation Reference

  • Core handler function that executes the start_conversation tool: validates args, creates conversation via ConversationManager, optionally sends initial message and polls for bot response.
    private async handleStartConversation(
      args: Record<string, unknown>,
      userContext?: UserContext
    ) {
      const { initialMessage } = validateToolArgs(StartConversationArgsSchema, args);
    
      try {
        // Create new conversation with user-specific client ID
        const clientId = userContext
          ? `user-${userContext.userId}-${Date.now()}`
          : `mcp-client-${Date.now()}`;
        const convState = await this.conversationManager.createConversation(clientId);
    
        // Associate conversation with user
        if (userContext) {
          this.associateConversationWithUser(userContext.userId, convState.conversationId);
        }
    
        let result: {
          conversationId: string;
          status: string;
          response?: string;
          activityId?: string;
        } = {
          conversationId: convState.conversationId,
          status: 'started',
        };
    
        // If initial message provided, send it
        if (initialMessage && typeof initialMessage === 'string') {
          const activityId = await this.client.sendActivity(
            {
              conversationId: convState.conversationId,
              activity: {
                type: 'message',
                from: { id: clientId, name: userContext?.name || 'MCP User' },
                text: initialMessage,
                timestamp: new Date().toISOString(),
                channelData: userContext
                  ? {
                      userId: userContext.userId,
                      userEmail: userContext.email,
                      tenantId: userContext.tenantId,
                    }
                  : undefined,
              },
            },
            convState.token
          );
    
          // Poll for response (same logic as send_message)
          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: convState.conversationId,
                watermark: convState.watermark,
              },
              convState.token
            );
    
            if (activitySet.watermark) {
              this.conversationManager.updateWatermark(convState.conversationId, activitySet.watermark);
            }
    
            const botActivities = activitySet.activities.filter(
              (a) => a.type === 'message' && a.from?.id !== clientId
            );
    
            if (botActivities.length > 0) {
              botActivities.forEach((activity) => {
                this.conversationManager.addToHistory(convState.conversationId, activity);
              });
    
              const latestBot = botActivities[botActivities.length - 1];
              botResponse = latestBot.text || '[No text response]';
              break;
            }
          }
    
          result.response = botResponse || '[No response received within timeout period]';
          result.activityId = activityId;
        }
    
        // Audit log
        this.logAudit({
          timestamp: Date.now(),
          userId: userContext?.userId,
          action: 'start_conversation',
          conversationId: convState.conversationId,
        });
    
        return createSuccessResponse(result);
      } catch (error) {
        throw new Error(
          `Failed to start conversation: ${error instanceof Error ? error.message : String(error)}`
        );
      }
    }
  • Zod schema defining input validation for start_conversation tool arguments (optional initialMessage).
    export const StartConversationArgsSchema = z.object({
      initialMessage: z.string().min(1, 'Initial message cannot be empty').optional(),
    });
    
    export type StartConversationArgs = z.infer<typeof StartConversationArgsSchema>;
  • Tool registration in ListToolsRequestHandler for stdio transport, defining name, description, and input schema.
      name: 'start_conversation',
      description: 'Start a new conversation with the Copilot Studio Agent',
      inputSchema: {
        type: 'object',
        properties: {
          initialMessage: {
            type: 'string',
            description: 'Optional first message to send',
          },
        },
      },
    },
  • Tool registration in HTTP transport handler for tools/list method.
    name: 'start_conversation',
    description: 'Start a new conversation with the Copilot Studio Agent',
    inputSchema: {
      type: 'object',
      properties: {
        initialMessage: {
          type: 'string',
          description: 'Optional first message to send',
        },
      },
    },
  • Helper method called by handler to create and manage conversation state, delegating actual DirectLine start to client.
    async createConversation(clientId: string): Promise<ConversationState> {
      // Get token from token manager
      const token = await this.tokenManager.getToken(clientId);
    
      // Start conversation with Direct Line
      const conversation = await this.client.startConversation(token);
    
      // Create state
      const state: ConversationState = {
        conversationId: conversation.conversationId,
        token: conversation.token,
        clientId,
        watermark: undefined,
        createdAt: Date.now(),
        lastActivity: Date.now(),
        messageHistory: [],
      };
    
      // Store state
      this.conversations.set(conversation.conversationId, state);
    
      // Update metrics
      this.metrics.totalCreated++;
      this.metrics.activeCount = this.conversations.size;
    
      // Schedule cleanup
      this.scheduleCleanup(conversation.conversationId);
    
      console.error(`[ConversationManager] Created conversation ${conversation.conversationId} for client ${clientId}`);
    
      return state;
    }

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observed

TDQS

B3.4/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 for transparency. It fails to disclose behavioral traits such as whether it resets prior context, returns a conversation ID, affects an existing conversation, or requires any prerequisites. The state-changing nature is implied but not explained.

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, front-loaded sentence with no redundancy or filler. It fully serves its immediate purpose in minimal words, earning a high score for conciseness.

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 simple one-parameter schema, the description omits critical context such as the return value, how it interacts with sibling tools, or whether it terminates an existing conversation. With no output schema or annotations, this lack of information leaves the agent uncertain about the tool's full behavior.

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 provides full coverage for the single optional parameter 'initialMessage' with a clear description. The tool description adds no additional semantic context about the parameter, so the baseline of 3 applies.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly specifies the action 'Start' and the resource 'a new conversation' with the target 'Copilot Studio Agent.' It distinguishes itself from sibling tools like send_message and end_conversation by explicitly indicating a new conversational session.

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?

The description only implies usage through the verb 'Start,' giving no explicit guidance on when to use this tool versus siblings, nor any exclusions or prerequisites. The context of the sibling names suggests lifecycle phases but is not articulated.

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