Model Context Protocol (MCP): Architecture & Custom Server
A deep dive into Model Context Protocol (MCP): JSON-RPC architecture, stdio/SSE transports, tools, resources, and building a custom MCP server in TypeScript.
As autonomous AI agents and coding assistants become essential developer tools, engineers face a recurring engineering hurdle: how can Large Language Models (LLMs) securely connect to internal repositories, local file systems, databases, and enterprise APIs without building proprietary integrations for every single model?
Anthropic’s open-source answer to this challenge is the Model Context Protocol (MCP) — an open standard designed to streamline how AI applications interact with external tools and external context.
Why MCP Matters#
Before MCP, the AI ecosystem suffered from an M × N Integration problem:
- If there are AI client applications (Claude Desktop, Cursor, VS Code, CLI agents…)
- And external tools or data sources (PostgreSQL, GitHub, Slack, local files, Jira…)
- Developers must maintain discrete point-to-point plugins.
Whenever a model vendor launches a new assistant or an API schema changes, developers are forced to rewrite integrations from scratch.
[!NOTE] MCP eliminates this complexity: It shifts integration from to . MCP functions as the USB-C port for AI applications. Any AI client implementing MCP can plug directly into any existing MCP server without code modifications.
Explain Like I’m 10 (ELI5)#
Picture an AI agent as a brilliant scholar seated inside an isolated room without windows (a pure LLM):
- Host & Client (The Doorway): Applications like Claude Desktop or Cursor act as personal assistants stationed right by the scholar’s desk.
- MCP Server (Specialized Drawers): Each MCP Server acts as an external drawer connecting to the outside world. One drawer holds internal documents, one provides access to a calculator, and another queries your GitHub repository.
- JSON-RPC (The Standardized Slip): Whenever the scholar needs fresh data or wishes to execute an action, they write a standardized request slip. The drawer returns results formatted precisely according to the agreement.
The Three Core MCP Primitives#
The MCP specification defines three distinct capabilities that a server can expose to AI clients:
1. Tools (Model-Controlled Actions)#
Executable functions that the LLM can invoke to perform side-effects or retrieve computations (e.g., query database records, execute bash scripts, create GitHub issues). The model dynamically selects which tool to execute and formats parameters according to an exposed JSON Schema.
2. Resources (Application-Controlled Data)#
Read-only data endpoints uniquely addressed via standardized URIs (e.g., file:///var/logs/app.log, postgres://users/schema). Clients or human operators can attach resources directly into conversation context to ground the LLM with factual background.
3. Prompts (User-Controlled Templates)#
Pre-configured prompt templates with dynamic arguments that guide users through structured workflows (e.g., “Analyze security vulnerabilities” or “Draft release notes”).
Transport Protocols#
MCP defines two standard communication mechanisms:
- stdio (Standard Input / Output): Communicates over local operating system processes. The Client launches the Server as a sub-process, sending messages via
stdinand listening onstdout. It provides zero network latency, native isolation, and maximum security for local desktop workflows. - SSE (Server-Sent Events) over HTTP: Designed for networked servers deployed on cloud infrastructure. Clients issue HTTP POST requests and receive continuous streaming updates over an open SSE connection.
Building a Custom TypeScript MCP Server#
Here is a runnable example of a custom MCP Server built using the official @modelcontextprotocol/sdk. This server registers:
- A Resource providing runtime configuration (
config://app-info) - A Tool computing repository file statistics (
analyze_workspace)
1. Project Setup#
mkdir my-custom-mcp-server
cd my-custom-mcp-server
bun init -y
bun add @modelcontextprotocol/sdk zodbash2. Server Implementation#
Create src/index.ts:
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import {
CallToolRequestSchema,
ListResourcesRequestSchema,
ListToolsRequestSchema,
ReadResourceRequestSchema,
} from '@modelcontextprotocol/sdk/types.js';
import { z } from 'zod';
// Initialize the MCP Server with metadata
const server = new Server(
{
name: 'project-analytics-server',
version: '1.0.0',
},
{
capabilities: {
resources: {},
tools: {},
},
},
);
// 1. Register Available Resources
server.setRequestHandler(ListResourcesRequestSchema, async () => {
return {
resources: [
{
uri: 'config://app-info',
name: 'Project Runtime Configuration',
mimeType: 'application/json',
},
],
};
});
// Handle Resource Reads
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
if (request.params.uri === 'config://app-info') {
return {
contents: [
{
uri: 'config://app-info',
mimeType: 'application/json',
text: JSON.stringify(
{
projectName: 'Dopana Engineering Hub',
environment: 'production',
supportedEngines: ['Bun', 'Node.js', 'Rust'],
},
null,
2,
),
},
],
};
}
throw new Error(`Resource not found: ${request.params.uri}`);
});
// 2. Register Available Tools
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [
{
name: 'analyze_workspace',
description: 'Analyze repository files and file extensions',
inputSchema: {
type: 'object',
properties: {
fileExtension: {
type: 'string',
description: 'File extension to analyze (e.g. ts, rs, py)',
},
},
required: ['fileExtension'],
},
},
],
};
});
// Handle Tool Executions
server.setRequestHandler(CallToolRequestSchema, async (request) => {
if (request.params.name === 'analyze_workspace') {
const ext = String(request.params.arguments?.fileExtension || 'ts');
return {
content: [
{
type: 'text',
text: JSON.stringify({
targetExtension: ext,
totalFilesFound: 42,
status: 'healthy',
summary: `Successfully completed analysis for .${ext} files`,
}),
},
],
};
}
throw new Error(`Tool not found: ${request.params.name}`);
});
// Connect via Stdio Transport
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error('MCP Server successfully connected via stdio transport.');
}
main().catch((err) => {
console.error('Fatal server startup error:', err);
process.exit(1);
});typescript[!TIP] Crucial Stdio Transport Rule: Never print diagnostic logs or raw messages to
stdout(console.log).stdoutis reserved exclusively for JSON-RPC messages. Always log debugging outputs tostderr(console.error), otherwise the client parser will throw JSON syntax errors.
3. Connecting to Claude Desktop or Cursor#
Configure your desktop client by adding the server to claude_desktop_config.json:
{
"mcpServers": {
"project-analytics": {
"command": "bun",
"args": ["run", "/absolute/path/to/my-custom-mcp-server/src/index.ts"]
}
}
}jsonRestart your client. The new hammer icon will appear in your chat window, and your assistant can autonomously trigger analyze_workspace.
Conclusion#
The Model Context Protocol establishes a clean boundary between model capabilities and domain-specific integrations. By adopting MCP, development teams ensure their internal infrastructure, tools, and databases remain accessible to whichever frontier AI models emerge next.