DEV Community

jasperstewart
jasperstewart

Posted on

Implementing Model Context Protocol: A Step-by-Step Guide

Building Your First MCP Integration

Building AI applications that need access to external data sources often feels like reinventing the wheel with each project. You write custom API wrappers, handle authentication separately for each service, and maintain brittle integration code that breaks when upstream services change. There's a better way to structure these integrations.

developer coding AI integration

By implementing the Model Context Protocol, you can build reusable, standardized connectors that work consistently across your AI applications. This tutorial walks through creating a complete MCP implementation, from initial setup to deployment. We'll build a practical example that demonstrates core concepts you can apply to any integration scenario.

Prerequisites and Setup

Before diving into implementation, ensure you have Node.js 18+ or Python 3.9+ installed. You'll also need an AI application that currently makes direct API calls or database queries. For this tutorial, we'll assume you have a basic understanding of REST APIs and asynchronous programming.

Install the official MCP SDK for your language of choice:

npm install @modelcontextprotocol/sdk
# or
pip install mcp
Enter fullscreen mode Exit fullscreen mode

Create a new project directory and initialize your workspace. The SDK includes TypeScript types and Python type hints that make development significantly easier, so configure your IDE accordingly.

Step 1: Define Your Context Provider

Start by identifying what context your AI application needs. For this example, we'll build a context provider that retrieves product information from a database. Create a new file called product-context-server.ts (or .py):

import { Server } from '@modelcontextprotocol/sdk/server';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio';

const server = new Server({
  name: 'product-context-server',
  version: '1.0.0'
}, {
  capabilities: {
    resources: {},
    tools: {}
  }
});
Enter fullscreen mode Exit fullscreen mode

This establishes the basic server structure that implements Model Context Protocol specifications. The capabilities object declares what your server can provide—in our case, both resources (data) and tools (actions).

Step 2: Implement Resource Handlers

Resources represent data your AI can access. Add a handler that retrieves product information:

server.setRequestHandler(ListResourcesRequestSchema, async () => {
  return {
    resources: [
      {
        uri: 'product://catalog',
        name: 'Product Catalog',
        mimeType: 'application/json'
      }
    ]
  };
});

server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
  if (request.params.uri === 'product://catalog') {
    const products = await fetchProductsFromDatabase();
    return {
      contents: [{
        uri: request.params.uri,
        mimeType: 'application/json',
        text: JSON.stringify(products)
      }]
    };
  }
  throw new Error('Resource not found');
});
Enter fullscreen mode Exit fullscreen mode

These handlers respond to Model Context Protocol requests from your AI application, translating them into database queries or API calls as needed.

Step 3: Add Tool Definitions

Tools allow your AI to take actions, not just read data. For teams exploring custom AI development, this capability enables powerful workflows. Define a tool that updates product inventory:

server.setRequestHandler(ListToolsRequestSchema, async () => {
  return {
    tools: [
      {
        name: 'update_inventory',
        description: 'Update product inventory quantity',
        inputSchema: {
          type: 'object',
          properties: {
            productId: { type: 'string' },
            quantity: { type: 'number' }
          },
          required: ['productId', 'quantity']
        }
      }
    ]
  };
});
Enter fullscreen mode Exit fullscreen mode

Step 4: Connect Your AI Application

On the client side, your AI application connects to the MCP server:

import { Client } from '@modelcontextprotocol/sdk/client';

const client = new Client({
  name: 'my-ai-app',
  version: '1.0.0'
});

const transport = new StdioClientTransport({
  command: 'node',
  args: ['product-context-server.js']
});

await client.connect(transport);
const resources = await client.listResources();
Enter fullscreen mode Exit fullscreen mode

Your application now communicates through the standardized protocol rather than directly calling databases or APIs.

Step 5: Error Handling and Logging

Implement robust error handling to make your MCP server production-ready:

server.onerror = (error) => {
  console.error('[MCP Error]', error);
};

process.on('SIGINT', async () => {
  await server.close();
  process.exit(0);
});
Enter fullscreen mode Exit fullscreen mode

Add logging for debugging and monitoring in production environments. The Model Context Protocol specification includes standard error codes that help clients handle failures gracefully.

Testing and Deployment

Test your implementation using the MCP inspector tool included with the SDK. It provides a UI for exploring your server's capabilities and sending test requests. Once verified, deploy your MCP server alongside your AI application or as a separate service, depending on your architecture.

For sensitive applications like Generative AI Audit Solutions, ensure you implement proper authentication and audit logging at the MCP layer to maintain compliance requirements.

Conclusion

You've now built a complete Model Context Protocol integration that your AI application can use to access external data and tools. This foundation scales to handle multiple data sources, complex authorization scenarios, and sophisticated tool interactions. The protocol handles the communication details, letting you focus on the unique logic your application requires.

Top comments (0)