Integrating Custom Servers via Model Context Protocol
Learn to build custom Node.js Model Context Protocol (MCP) servers to securely expose system tools, file listings, and environments to AI agents.
playwright-v1-49-matrix
Integrating Custom Servers via Model Context Protocol
The AI ecosystem is shifting rapidly. AI models are transitioning from simple chat interfaces to active workspace partners. To accomplish this, agents need a standardized way to access tools, files, and external directories. This guide explores the Model Context Protocol (MCP) and how to write custom servers.
Introduction
Exposing local resources directly to LLM models introduces security risks and development friction. Model Context Protocol acts as an open standard to connect developer tools to LLM providers. By defining uniform schemas, models can safely interact with filesystems and run build procedures.
This standard decouples agent runners from host systems. It establishes a secure interface for file inspection and terminal command validation.
Core Architecture of MCP
The protocol is designed around a Client-Server model. This structure guarantees that LLM clients remain isolated from raw OS-level permissions:
graph TD
Client["AI Agent Runner (MCP Client)"] -->JSON-RPC 2.0 / stdio
Server["Local MCP Server"]
Server -->Read/Write Allowed Paths
Directory["System Directory / Tool Execution"]
Server -->Sanitizes Output
ClientCommunication occurs via JSON-RPC 2.0 protocols over standard input/output (stdio) or Server-Sent Events (SSE).
Communication Sequence
An agent execution follows this request-response flow to discover and call system tools:
sequenceDiagram
participant Agent as Agent Client (e.g. Claude)
participant Server as MCP Server
participant System as Host OS File System
Agent->>Server: List available tools (tools/list)
Server-->>Agent: Return tool schemas (JSON)
Agent->>Agent: Decide to call tool
Agent->>Server: Call tool with parameters (tools/call)
Server->>Server: Validate parameters & safety rules
Server->>System: Execute action on host
System-->>Server: Return output/file content
Server-->>Agent: Send sanitized response backCreating a Model Context Protocol Server
Follow these steps to construct a Node.js MCP server using TypeScript.
1. Initialize Project Configuration
Configure a project directory and setup dependencies inside your package:
// package.json configuration summary
{
"name": "mcp-system-helper",
"version": "1.0.0",
"type": "module",
"dependencies": {
"@modelcontextprotocol/sdk": "^0.6.0"
}
}2. Implement the Server Instance
Write the Node.js service using stdio transports to communicate with AI agents:
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
// Initialize the server definition
const server = new Server(
{ name: 'mcp-system-helper', version: '1.0.0' },
{ capabilities: { tools: {} } }
);
// Define available tools list
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: [
{
name: 'get_env_variable',
description: 'Get an environment variable by name',
inputSchema: {
type: 'object',
properties: { name: { type: 'string' } },
required: ['name'],
},
},
],
}));
// Setup transport connection
const transport = new StdioServerTransport();
await server.connect(transport);
console.error('MCP System Helper running over stdio');3. Handle Tool Execution Requests
Add logic to resolve variables when tools are triggered by the client:
// Register handler for tool executions
server.setRequestHandler(CallToolRequestSchema, async (request) => {
if (request.params.name === 'get_env_variable') {
const varName = request.params.arguments?.name as string;
const value = process.env[varName]
'Not Defined';
// Return structured text result
return {
content: [{ type: 'text', text: Value: ${value} }],
};
}
throw new Error(Tool ${request.params.name} not found);
});Protocol Capabilities Compared
The table below contrasts standard API integrations with Model Context Protocol configurations.
| Characteristic | Traditional API Wrappers | Model Context Protocol (MCP) |
|---|---|---|
| Data Schema | Customized per endpoint | Uniform JSON-RPC 2.0 standards |
| Transport Protocol | Custom HTTP requests | Stdio channels or SSE transports |
| Host Sandboxing | Requires custom filters | Integrated parameter schemas |
| Tool Auto-Discovery | Manual client configuration | Automatic tools list serialization |
| Model Compatibility | Locked to specific LLM SDKs | Multi-model transport integration |
Best Practices and Security Constraints
Here are a few key practices:
Common Mistakes to Avoid
| Bad Pattern | Recommended Alternative |
| Exposing global exec shell | Limit actions to specific named functions (e.g. read_file) |
| Allowing unrestricted file paths | Validate absolute paths against a whitelist directory |
| Committing secrets in config | Load variables via environment files at boot |
Frequently Asked Questions
What transport options does MCP support?
It supports standard input/output streams (stdio) for local CLI utilities and Server-Sent Events (SSE) for remote servers.
Can I run an MCP server on a remote machine?
Yes. Connect the server via SSE endpoints and authenticate clients through standard web security tokens.
How do agents find new tools?
The runner queries the client tools list schema. This returns the names, parameters, and descriptions of all registered modules.
Can I write MCP servers in Python?
Yes. The protocol maintains official SDK libraries in both Python and Node.js to assist server generation.
Does MCP support streaming responses?
Yes. Stdio streams and SSE channels support continuous data delivery for larger text payloads.
How does the server handle concurrency?
The standard SDK processes JSON-RPC requests asynchronously, allowing multiple requests to compile simultaneously.
Is Docker recommended for local servers?
Yes. It prevents AI agents from executing commands that modify critical boot settings.
What models support MCP tools?
Any modern LLM that supports function calling can utilize MCP clients via wrapper scripts.
How do I debug tool parameter errors?
Run the server individually and pipe test inputs manually into stdin to capture errors before running agents.
Can MCP read system logs?
Only if you write a tool specifically mapped to retrieve log folders with correct OS access rights.
Summary
Exposing system tools using Model Context Protocol simplifies AI agent integrations. Building custom Node.js servers establishes a clean interface for automation.
Related Articles
About The Author
PlaywrightPad Editorial reports on Chromium engines, E2E test optimizations, and AI integration specifications.
Newsletter
Get weekly browser reports sent directly to your inbox.