Model Context Protocol (MCP) is a standard for connecting LLMs to external tools and data sources. It enables AI assistants to safely interact with databases, APIs, and other systems. This guide covers building MCP servers for common use cases.
MCP Server Basics
// Basic MCP Server
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
const server = new Server(
{
name: 'my-mcp-server',
version: '1.0.0',
},
{
capabilities: {
tools: {},
resources: {},
},
}
);
// Define a tool
server.setRequestHandler('tools/list', async () => ({
tools: [
{
name: 'search_database',
description: 'Search the database for records',
inputSchema: {
type: 'object',
properties: {
query: { type: 'string', description: 'Search query' },
limit: { type: 'number', description: 'Max results' },
},
required: ['query'],
},
},
],
}));
// Handle tool calls
server.setRequestHandler('tools/call', async (request) => {
if (request.params.name === 'search_database') {
const { query, limit = 10 } = request.params.arguments;
const results = await db.search(query, limit);
return { content: [{ type: 'text', text: JSON.stringify(results) }] };
}
throw new Error('Unknown tool');
});
// Start server
const transport = new StdioServerTransport();
await server.connect(transport);Resources and Prompts
// MCP Resources (data the LLM can read)
server.setRequestHandler('resources/list', async () => ({
resources: [
{
uri: 'db://users/schema',
name: 'Database Schema',
description: 'Current database schema',
mimeType: 'application/json',
},
],
}));
server.setRequestHandler('resources/read', async (request) => {
if (request.params.uri === 'db://users/schema') {
const schema = await db.getSchema();
return {
contents: [{
uri: request.params.uri,
mimeType: 'application/json',
text: JSON.stringify(schema),
}],
};
}
throw new Error('Resource not found');
});Best Practices
MCP Best Practices
Security:
- Validate all inputs
- Implement rate limiting
- Use read-only access where possible
- Log all tool invocations
Design:
- Keep tools focused and atomic
- Provide clear descriptions
- Return structured data
- Handle errors gracefully
Conclusion
MCP enables powerful AI integrations by providing a standard protocol for tool use. Start with simple read-only tools and expand capabilities as you understand the patterns.
Need help building AI integrations? Contact Jishu Labs for expert AI development consulting.
About Sarah Johnson
Sarah Johnson is the CTO at Jishu Labs with expertise in AI systems and tool integrations.