Building Your First AI Agent
Step-by-step guide to creating an AI agent with MCP Server tools
Building Your First AI Agent
Learn how to create a powerful AI agent that can interact with external tools and services using MCP Server.
What You'll Build
In this guide, you'll create an AI agent that can:
Prerequisites
Step 1: Set Up Your Project
mkdir my-ai-agent
cd my-ai-agent
npm init -y
npm install @mcpserver/sdk openai
Step 2: Create Your Agent
import { MCPClient } from '@mcpserver/sdk';
import OpenAI from 'openai';
const mcp = new MCPClient({
apiKey: process.env.MCP_API_KEY,
});
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
async function runAgent(userMessage: string) {
// Get available tools from MCP Server
const tools = await mcp.tools.list();
// Call OpenAI with tools
const response = await openai.chat.completions.create({
model: 'gpt-4',
messages: [{ role: 'user', content: userMessage }],
tools: tools.map(t => ({
type: 'function',
function: {
name: t.name,
description: t.description,
parameters: t.parameters,
}
})),
});
// Handle tool calls
const toolCall = response.choices[0].message.tool_calls?.[0];
if (toolCall) {
const result = await mcp.tools.execute({
tool: toolCall.function.name,
parameters: JSON.parse(toolCall.function.arguments),
});
return result;
}
return response.choices[0].message.content;
}
Step 3: Test Your Agent
const result = await runAgent('What are our top 10 customers by revenue?');
console.log(result);
Advanced Features
Adding Custom Tools
You can register custom tools specific to your use case:
await mcp.tools.register({
name: 'send-email',
description: 'Send an email to a user',
parameters: {
type: 'object',
properties: {
to: { type: 'string' },
subject: { type: 'string' },
body: { type: 'string' },
},
required: ['to', 'subject', 'body'],
},
handler: async (params) => {
// Your email sending logic
await sendEmail(params);
return { success: true };
},
});
Multi-Turn Conversations
Handle complex conversations with context:
const conversation = await mcp.conversations.create();
await conversation.addMessage('user', 'Who are our top customers?');
const response1 = await conversation.run();
await conversation.addMessage('user', 'Send them a thank you email');
const response2 = await conversation.run();
Best Practices
1. Error Handling: Always wrap tool execution in try-catch blocks
2. Rate Limiting: Implement exponential backoff for API calls
3. Caching: Cache frequently accessed data to reduce latency
4. Monitoring: Log all tool executions for debugging