> ## Documentation Index
> Fetch the complete documentation index at: https://docs.layercode.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Connect to MCP servers with AI SDK

> How to get your voice agents to use Model Context Protocol (MCP) tools with AI SDK and Layercode

It can be useful for your voice agents to use [Model Context Protocol (MCP)](https://modelcontextprotocol.io) 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](https://docs.layercode.com/how-tos/tool-calling-js)

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.

```ts theme={null}
import { createGoogleGenerativeAI } from '@ai-sdk/google';
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: createGoogleGenerativeAI({ apiKey: process.env.GOOGLE_GENERATIVE_AI_API_KEY })('gemini-2.5-flash-lite'),
        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();
    }
  });
};
```
