MCP Endpoint Setup
Step-by-step guide to setting up MCP endpoints for ChatGPT SDK integration
MCP Endpoint Setup Guide
This guide walks you through setting up MCP (Model Context Protocol) endpoints to enable ChatGPT to interact with your application.
Prerequisites
- OpenAI API key
- Next.js 16+ application
@ai-sdk/openaipackage installed
Installation
bun add ai @ai-sdk/openai zodBasic Setup
1. Create the API Route
Create a new file at app/api/chat/route.ts:
import { openai } from '@ai-sdk/openai';
import { streamText } from 'ai';
import { z } from 'zod';
export async function POST(req: Request) {
const { messages } = await req.json();
const result = streamText({
model: openai('gpt-4o'),
messages,
tools: {
// Define your MCP tools here
searchEmails: {
description: 'Search emails in the inbox',
parameters: z.object({
query: z.string().describe('Search query'),
limit: z.number().optional().describe('Maximum results'),
}),
execute: async ({ query, limit = 10 }) => {
// Your search implementation
return { emails: [] };
},
},
},
});
return result.toDataStreamResponse();
}2. Configure Environment Variables
Add to your .env.local:
OPENAI_API_KEY=sk-...3. Create the Chat Component
'use client';
import { useChat } from 'ai/react';
export function Chat() {
const { messages, input, handleInputChange, handleSubmit } = useChat({
api: '/api/chat',
});
return (
<div>
{messages.map(m => (
<div key={m.id}>
<strong>{m.role}:</strong> {m.content}
</div>
))}
<form onSubmit={handleSubmit}>
<input
value={input}
onChange={handleInputChange}
placeholder="Ask something..."
/>
<button type="submit">Send</button>
</form>
</div>
);
}Advanced Configuration
Custom Tool Execution
const result = streamText({
model: openai('gpt-4o'),
messages,
maxSteps: 5, // Allow multiple tool calls
tools: {
sendEmail: {
description: 'Send an email',
parameters: z.object({
to: z.string().email(),
subject: z.string(),
body: z.string(),
}),
execute: async (params) => {
// Validate user permissions
// Send email via your email service
return { success: true, messageId: '...' };
},
},
},
});Error Handling
export async function POST(req: Request) {
try {
const { messages } = await req.json();
const result = streamText({
model: openai('gpt-4o'),
messages,
tools: { /* ... */ },
});
return result.toDataStreamResponse();
} catch (error) {
console.error('Chat API error:', error);
return new Response(
JSON.stringify({ error: 'Failed to process request' }),
{ status: 500, headers: { 'Content-Type': 'application/json' } }
);
}
}Testing Your Setup
- Start your development server:
bun run dev - Navigate to your chat page
- Test tool calling with prompts like:
- "Search for emails about billing"
- "Send an email to team@example.com"