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;
    }
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It states the action but doesn't explain what 'starting a conversation' entails—whether it creates a persistent session, requires authentication, has rate limits, or what the expected response format is. This leaves significant behavioral gaps.

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, clear sentence with zero wasted words. It's front-loaded with the core purpose and appropriately sized for the tool's complexity, making it highly efficient.

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?

Given no annotations and no output schema, the description is incomplete. It doesn't explain what happens after starting a conversation (e.g., returns a conversation ID, initiates a session) or address behavioral aspects like error handling. For a tool that likely creates a stateful interaction, this leaves critical context missing.

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 has 100% description coverage, with the single parameter 'initialMessage' documented as 'Optional first message to send'. The description doesn't add any meaning beyond this, such as message format constraints or examples, so it meets the baseline for high schema coverage without compensation.

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 ('Start a new conversation') and the target ('with the Copilot Studio Agent'), providing a specific verb+resource combination. However, it doesn't explicitly differentiate from sibling tools like 'send_message' or 'get_conversation_history', which prevents a perfect score.

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 like 'send_message' (which might be for ongoing conversations) or 'end_conversation'. There's no mention of prerequisites, context requirements, or explicit exclusions, leaving usage unclear.

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