Skip to main content
It can be useful for your voice agents to use Model Context Protocol (MCP) to fetch live data or perform external actions — for example, retrieving docs, querying databases, or running custom APIs. This guide shows you how to connect your AI SDK app to an MCP server and expose those tools to your Layercode voice agent.

Prerequisites

This guide assumes you already have tool calling set up and working with Layercode. If not, start here first:
👉 Tool calling in Next.js with Layercode
Once that’s working, you can extend your agent with MCP-based tools.

Example Setup

Note: The MCP URL https://docs.layercode.com/mcp below is just an example endpoint that connects to the Layercode Docs MCP server.
Replace this with your own MCP server URL — for example, one that connects to your company’s data, APIs, or private knowledge.
import { createOpenAI } from '@ai-sdk/openai';
import { streamText, stepCountIs, experimental_createMCPClient, tool } from 'ai';
import { streamResponse } from '@layercode/node-server-sdk';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
import z from 'zod';

export const POST = async (request: Request) => {
  const requestBody = await request.json();
  const { conversation_id, text, turn_id } = requestBody;

  return streamResponse(requestBody, async ({ stream }) => {
    // ✅ Create a fresh MCP transport per request
    const transport = new StreamableHTTPClientTransport(new URL('https://docs.layercode.com/mcp'));
    const docsMCP = await experimental_createMCPClient({ transport });

    try {
      const docsTools = await docsMCP.tools();

      const weather = tool({
        description: 'Get the weather in a location',
        inputSchema: z.object({
          location: z.string().describe('The location to get the weather for')
        }),
        execute: async ({ location }) => ({
          location,
          temperature: 72 + Math.floor(Math.random() * 21) - 10
        })
      });

      const { textStream } = streamText({
        model: openai('gpt-4o-mini'),
        system: 'You are a helpful assistant.',
        messages: [{ role: 'user', content: text }],
        tools: { weather, ...docsTools },
        toolChoice: 'auto',
        stopWhen: stepCountIs(10),
        onFinish: async ({ response }) => {
          console.log('MCP Response Complete', response);
          stream.end();
        }
      });

      await stream.ttsTextStream(textStream);
    } finally {
      // ✅ Clean up the MCP connection
      await docsMCP.close();
    }
  });
};
I