Setting Up MCP Servers
1. Installing Existing MCP Servers
| Server | Installation Command | Notes |
|---|---|---|
| MCP Server for Python | pip install mcp-server |
Official Python implementation of MCP server |
| MCP Server for Node.js | npm install -g @mcp/server |
Node.js-based MCP server with TypeScript support |
| MCP Server for Java | mvn install org.mcp:server |
Java-based MCP server with Spring Boot integration |
Note: Ensure Python 3.9+ is installed before installing the Python MCP server.
2. Configuring MCP Server Registry Files
Example: Basic MCP Server Configuration
{
"name": "my-ai-server",
"version": "1.0.0",
"description": "AI-assisted development server",
"entrypoint": "./server.js",
"capabilities": [
"code-completion",
"code-generation"
]
}
| Field | Description | Required |
|---|---|---|
| name | Unique identifier for the MCP server | Yes |
| version | Version of the MCP server (e.g., 1.0.0) | Yes |
| description | Human-readable description of the server | No |
| entrypoint | Path to the server executable or script | Yes |
| capabilities | List of supported AI features (e.g., code-completion, code-generation) | Yes |
Note: The registry file must be placed in the
.mcp directory within the project root.
Warning: Ensure that all paths in the registry file are relative to the project root.
3. Building a Custom MCP Server
Example: Basic MCP Server Setup
const { McpServer } = require("@modelcontextprotocol/sdk");
const server = new McpServer({
name: "my-custom-server",
version: "1.0.0"
});
server.registerHandler("model/list", async () => {
return {
models: [
{
id: "gpt-4",
name: "GPT-4",
description: "Advanced language model"
}
]
};
});
server.start();
| Property | Description | Values |
|---|---|---|
| name | Unique identifier for the MCP server | string |
| version | Version of the MCP server implementation | string |
| capabilities | Supported MCP capabilities | object |
Note: The MCP server must implement the required capabilities to communicate with AI assistants.
Example: Registering a Custom Handler
server.registerHandler("tool/invoke", async (request) => {
const { toolName, parameters } = request;
if (toolName === "weather") {
return {
result: `Current weather in ${parameters.city}: 22°C, sunny`
};
}
throw new Error(`Unknown tool: ${toolName}`);
});
Key Steps to Build an MCP Server
- Initialize the MCP server with name and version
- Define supported capabilities
- Register handlers for MCP methods
- Start the server to listen for connections
4. Registering MCP Tools and Handlers
| Tool/Handler | Type | Description | Registration Method |
|---|---|---|---|
| mcp.tool.register | function |
Registers a new tool with the MCP server | POST /tools |
| mcp.handler.register | function |
Registers a new handler for MCP events | POST /handlers |
Example: Registering a Tool
const tool = {
name: "CodeCompletionTool",
description: "Provides code completion suggestions",
parameters: {
language: "javascript",
maxTokens: 100
}
};
fetch("http://localhost:3000/tools", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(tool)
});
Example: Registering a Handler
const handler = {
event: "onCodeChange",
callback: function(event) {
console.log("Code changed: " + event.code);
}
};
fetch("http://localhost:3000/handlers", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(handler)
});
Note: Handlers must be registered before the corresponding events occur to ensure proper event capture.
5. Testing MCP Servers Locally
Example: Local MCP Server Test Setup
mkdir mcp-test-server
cd mcp-test-server
npm init -y
npm install @modelcontextprotocol/sdk
| Command | Description | Notes |
|---|---|---|
| npx mcp-server | Starts a local MCP server instance | Uses default configuration |
| npx mcp-server --port 3000 | Starts MCP server on port 3000 | Customizable port binding |
| npx mcp-server --config ./mcp-config.json | Loads server config from file | Supports JSON configuration files |
Note: Ensure the MCP server is running before connecting clients.
Example: Client Connection Test
import { Client } from '@modelcontextprotocol/sdk';
const client = new Client({
serverUrl: 'http://localhost:3000',
});
await client.connect();
console.log('Connected to MCP server');
Testing Steps
- Start MCP server with
npx mcp-server - Verify server is listening on expected port
- Test health endpoint with
curl - Connect client to server using SDK
6. Deploying Remote MCP Servers
Deploying remote MCP servers involves setting up a server environment that can handle incoming connections from clients and manage AI-assisted development workflows. This section outlines the steps to deploy and configure an MCP server for remote access.
| Component | Description | Deployment Options |
|---|---|---|
| MCP Server | Core server component that handles protocol communication and AI model interactions | Node.js, Python, Go |
| Authentication | Secure access to the MCP server using tokens or API keys | JWT, OAuth2, API Keys |
| Networking | Configuration for exposing the server to external clients | HTTPS, WebSocket, gRPC |
Example: Deploying an MCP Server with Node.js
const express = require('express');
const { createServer } = require('http');
const { Server } = require('socket.io');
const app = express();
const server = createServer(app);
const io = new Server(server, {
cors: {
origin: '*',
},
});
io.on('connection', (socket) => {
console.log('Client connected');
socket.on('message', (data) => {
// Handle MCP protocol messages
console.log('Received:', data);
});
});
server.listen(3000, () => {
console.log('MCP server running on port 3000');
});
Note: Ensure that the server is configured to handle secure WebSocket connections and that all client communications are encrypted using TLS.
7. Managing MCP Server Environment Variables
| Variable | Description | Default Value | Notes |
|---|---|---|---|
| MCP_SERVER_PORT | Port to bind the MCP server | 3000 |
Can be overridden via CLI or config |
| MCP_SERVER_HOST | Host address to bind the MCP server | localhost |
Use 0.0.0.0 to allow external connections |
| MCP_SERVER_LOG_LEVEL | Log level for MCP server logs | info |
Options: debug, info, warn, error |
| MCP_SERVER_CONFIG_PATH | Path to the MCP server configuration file | ./mcp-config.json |
Must be a valid JSON file path |
| MCP_SERVER_MODEL_ID | ID of the AI model to use for inference | gpt-4-turbo |
Must be a valid model identifier supported by the backend |
Example: Setting Environment Variables
export MCP_SERVER_PORT=8080
export MCP_SERVER_HOST=0.0.0.0
export MCP_SERVER_LOG_LEVEL=debug
export MCP_SERVER_CONFIG_PATH=/etc/mcp/config.json
export MCP_SERVER_MODEL_ID=gpt-4o
Note: Environment variables can be overridden by command-line flags or configuration files. The precedence order is: CLI flags > Environment variables > Default values.
8. Securing MCP Server Credentials
Note: This section covers securing credentials for MCP (Model Control Protocol) servers, which are used in AI-assisted development environments to manage model interactions and data flows.
| Credential Type | Description | Security Best Practices | Examples |
|---|---|---|---|
| API Keys | Secret keys used to authenticate requests to MCP servers. | Store in environment variables or secure vaults. Rotate keys regularly. | API_KEY=sk-abc123xyz |
| OAuth Tokens | Bearer tokens for authorization to MCP server endpoints. | Use short-lived tokens. Implement refresh token logic. | BEARER_TOKEN=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... |
| Certificate Files | SSL/TLS certificates for secure communication. | Use only trusted CA-signed certs. Store in encrypted storage. | cert.pem, key.pem |
Example: Environment-Based API Key Usage
const mcpConfig = {
apiKey: process.env.MCP_API_KEY,
serverUrl: 'https://mcp.example.com',
timeout: 5000
};
Example: Secure Token Refresh Logic
async function refreshOAuthToken() {
const response = await fetch('/auth/refresh', {
method: 'POST',
headers: { 'Authorization': `Bearer ${oldToken}` }
});
const data = await response.json();
return data.newToken;
}
Key Security Practices
- Never hardcode credentials in source files.
- Use secrets management tools (e.g., AWS Secrets Manager, HashiCorp Vault).
- Implement token rotation and automatic refresh.
- Validate and sanitize all inputs to MCP server endpoints.
Warning: Exposing MCP server credentials in logs or client-side code can lead to unauthorized access and data breaches.