Getting Started with MCP

Begin your journey with the Model Context Protocol

Introduction

This guide will help you get started with the Model Context Protocol (MCP), whether you're building an AI application that needs to connect to external data sources or creating an MCP server to expose your data and tools to AI models.

We'll cover the basics of setting up both MCP clients and servers, with examples in different programming languages.

Prerequisites

Before you begin, make sure you have the following:

Installation

The first step is to install the appropriate MCP SDK for your programming language:

TypeScript/JavaScript

npm install @modelcontextprotocol/client
npm install @modelcontextprotocol/server

Python

pip install mcp-client
pip install mcp-server

Java

// Add to your Maven pom.xml

  io.modelcontextprotocol
  mcp-client
  1.0.0



  io.modelcontextprotocol
  mcp-server
  1.0.0

C#

dotnet add package ModelContextProtocol.Client
dotnet add package ModelContextProtocol.Server

Building an MCP Client

An MCP client is an application that connects to MCP servers to access data and tools. Here's how to create a basic MCP client:

TypeScript/JavaScript Example

import { MCPClient } from '@modelcontextprotocol/client';

async function main() {
  // Create an MCP client
  const client = new MCPClient();
  
  // Connect to an MCP server (e.g., filesystem server)
  await client.connect({
    transport: 'stdio',
    command: 'npx',
    args: ['-y', '@modelcontextprotocol/server-filesystem', '/path/to/directory']
  });
  
  // List available tools
  const tools = await client.listTools();
  console.log('Available tools:', tools);
  
  // Call a tool
  const result = await client.callTool({
    name: 'readFile',
    parameters: { path: 'example.txt' }
  });
  console.log('File contents:', result);
  
  // Disconnect when done
  await client.disconnect();
}

main().catch(console.error);

Python Example

from mcp_client import MCPClient
import asyncio

async def main():
    # Create an MCP client
    client = MCPClient()
    
    # Connect to an MCP server (e.g., filesystem server)
    await client.connect(
        transport='stdio',
        command='npx',
        args=['-y', '@modelcontextprotocol/server-filesystem', '/path/to/directory']
    )
    
    # List available tools
    tools = await client.list_tools()
    print('Available tools:', tools)
    
    # Call a tool
    result = await client.call_tool(
        name='readFile',
        parameters={'path': 'example.txt'}
    )
    print('File contents:', result)
    
    # Disconnect when done
    await client.disconnect()

asyncio.run(main())

Building an MCP Server

An MCP server exposes data and tools to MCP clients. Here's how to create a basic MCP server:

TypeScript/JavaScript Example

import { createServer, MCPTool } from '@modelcontextprotocol/server';

// Define a tool
const greetingTool: MCPTool = {
  name: 'greeting',
  description: 'Returns a greeting message',
  parameters: {
    type: 'object',
    properties: {
      name: {
        type: 'string',
        description: 'Name to greet'
      }
    },
    required: ['name']
  },
  handler: async (params) => {
    return `Hello, ${params.name}!`;
  }
};

// Create an MCP server
const server = createServer({
  name: 'greeting-server',
  description: 'A server that provides greeting functionality',
  version: '1.0.0',
  tools: [greetingTool]
});

// Start the server
server.start();

Python Example

from mcp_server import create_server, MCPTool

# Define a tool
greeting_tool = MCPTool(
    name='greeting',
    description='Returns a greeting message',
    parameters={
        'type': 'object',
        'properties': {
            'name': {
                'type': 'string',
                'description': 'Name to greet'
            }
        },
        'required': ['name']
    }
)

# Define the handler function
async def greeting_handler(params):
    return f"Hello, {params['name']}!"

# Attach the handler
greeting_tool.handler = greeting_handler

# Create an MCP server
server = create_server(
    name='greeting-server',
    description='A server that provides greeting functionality',
    version='1.0.0',
    tools=[greeting_tool]
)

# Start the server
server.start()

Using Existing MCP Servers

Instead of building your own MCP server from scratch, you can use existing MCP servers to add functionality to your applications:

Filesystem Server

// Install the filesystem server
npm install -g @modelcontextprotocol/server-filesystem

// Connect to the server in your client
await client.connect({
  transport: 'stdio',
  command: 'npx',
  args: ['@modelcontextprotocol/server-filesystem', '/path/to/directory']
});

Git Server

// Install the Git server
npm install -g @modelcontextprotocol/server-git

// Connect to the server in your client
await client.connect({
  transport: 'stdio',
  command: 'npx',
  args: ['@modelcontextprotocol/server-git', '/path/to/repository']
});

Postgres Server

// Install the Postgres server
npm install -g @modelcontextprotocol/server-postgres

// Connect to the server in your client
await client.connect({
  transport: 'stdio',
  command: 'npx',
  args: ['@modelcontextprotocol/server-postgres', '--connection-string', 'postgresql://user:password@localhost:5432/database']
});

Google Drive Server

// Install the Google Drive server
npm install -g @modelcontextprotocol/server-google-drive

// Connect to the server in your client
await client.connect({
  transport: 'stdio',
  command: 'npx',
  args: ['@modelcontextprotocol/server-google-drive', '--credentials-file', '/path/to/credentials.json']
});

Connecting Claude to MCP Servers

Claude can connect to MCP servers through various interfaces, including Claude Desktop and the Claude API. Here's how to use MCP with Claude:

Claude Desktop

Claude Desktop provides a user-friendly interface for connecting Claude to MCP servers:

  1. Install Claude Desktop from Anthropic's website.
  2. Open Claude Desktop and start a conversation.
  3. Click on the "Connect" button in the interface.
  4. Select the MCP server you want to connect to (e.g., filesystem, Git).
  5. Follow the prompts to configure the server connection.
  6. Once connected, Claude can access the data and tools provided by the MCP server.

Claude API with MCP

For programmatic access, you can use the Claude API with MCP:

import { MCPClient } from '@modelcontextprotocol/client';
import { Claude } from '@anthropic-ai/sdk';

async function main() {
  // Create an MCP client
  const mcpClient = new MCPClient();
  
  // Connect to an MCP server
  await mcpClient.connect({
    transport: 'stdio',
    command: 'npx',
    args: ['-y', '@modelcontextprotocol/server-filesystem', '/path/to/directory']
  });
  
  // List available tools
  const tools = await mcpClient.listTools();
  
  // Create a Claude client
  const claude = new Claude({
    apiKey: process.env.ANTHROPIC_API_KEY
  });
  
  // Send a message to Claude with MCP tools
  const response = await claude.messages.create({
    model: 'claude-3-opus-20240229',
    max_tokens: 1024,
    messages: [
      {
        role: 'user',
        content: 'Please read the file example.txt and summarize its contents.'
      }
    ],
    tools: tools
  });
  
  console.log(response.content);
}

main().catch(console.error);

Common Use Cases

Here are some common use cases for MCP and examples of how to implement them:

Document Processing

Use MCP to enable AI models to read, analyze, and process documents:

// Connect to the filesystem server
await client.connect({
  transport: 'stdio',
  command: 'npx',
  args: ['@modelcontextprotocol/server-filesystem', '/path/to/documents']
});

// Read a document
const content = await client.callTool({
  name: 'readFile',
  parameters: { path: 'report.txt' }
});

Database Queries

Use MCP to enable AI models to query databases:

// Connect to the Postgres server
await client.connect({
  transport: 'stdio',
  command: 'npx',
  args: ['@modelcontextprotocol/server-postgres', '--connection-string', 'postgresql://user:password@localhost:5432/database']
});

// Execute a query
const results = await client.callTool({
  name: 'executeQuery',
  parameters: { query: 'SELECT * FROM users LIMIT 10' }
});

Code Repository Access

Use MCP to enable AI models to access code repositories:

// Connect to the Git server
await client.connect({
  transport: 'stdio',
  command: 'npx',
  args: ['@modelcontextprotocol/server-git', '/path/to/repository']
});

// List files in the repository
const files = await client.callTool({
  name: 'listFiles',
  parameters: { path: '.' }
});

Web Browsing

Use MCP to enable AI models to browse the web:

// Connect to the Puppeteer server
await client.connect({
  transport: 'stdio',
  command: 'npx',
  args: ['@modelcontextprotocol/server-puppeteer']
});

// Navigate to a webpage
const content = await client.callTool({
  name: 'getPageContent',
  parameters: { url: 'https://example.com' }
});

Best Practices

Here are some best practices to follow when working with MCP:

Security Considerations

  • Limit Access: Configure MCP servers to access only the resources that are necessary for the application.
  • Validate Inputs: Implement proper input validation for tool parameters to prevent security vulnerabilities.
  • Use Local Transport: For sensitive operations, use stdio transport to ensure data doesn't leave the local machine.
  • Secure API Keys: Protect API keys and credentials used by MCP servers.

Performance Optimization

  • Cache Tool Lists: Cache the results of listTools calls to reduce latency.
  • Optimize Data Transfer: Transfer only the necessary data between clients and servers to minimize overhead.
  • Implement Pagination: For tools that return large amounts of data, implement pagination to avoid performance issues.
  • Use Efficient Serialization: Choose efficient serialization formats for data exchange between clients and servers.

Tool Design

  • Clear Descriptions: Provide clear and detailed descriptions for tools and parameters to help AI models understand how to use them.
  • Consistent Naming: Use consistent naming conventions for tools and parameters across your MCP servers.
  • Atomic Operations: Design tools to perform atomic operations that can be composed to achieve complex tasks.
  • Error Handling: Implement robust error handling to provide informative error messages when tools fail.

Testing and Debugging

  • Unit Testing: Write comprehensive unit tests for your MCP servers and tools.
  • Integration Testing: Test the interaction between your MCP clients and servers to ensure compatibility.
  • Logging: Implement detailed logging in your MCP servers to help debug issues.
  • Mocking: Use mock MCP servers for testing to isolate client code from external dependencies.

Next Steps

Now that you've learned the basics of MCP, here are some next steps to explore:

Explore the Ecosystem

Check out the MCP Ecosystem page to discover available MCP servers, tools, and resources.

Dive into the Architecture

Learn more about the MCP Architecture to understand the technical details of how MCP works.

Join the Community

Join the MCP community forums to ask questions, share ideas, and collaborate with other developers.

Build Your Own MCP Server

Create your own MCP server to expose your data and tools to AI models, and consider contributing it to the community.