mcp-integration-scaffold-ts
A robust TypeScript foundation for creating bespoke Model Context Protocol (MCP) execution engines. This scaffold facilitates secure integration between cognitive agents and disparate external data repositories or API endpoints, featuring native support for IP address introspection utilities and comprehensive command-line tooling.
Author

aashari
Quick Info
Actions
Tags
TypeScript MCP Engine Seed Project
This repository offers a production-grade, opinionated starting point for architects developing custom Model Context Protocol (MCP) servers using TypeScript. It enforces a rigorous, multi-layered architectural pattern, includes a functional demonstration (IP lookup), and provides a complete developer toolchain necessary for immediate deployment and debugging.
Core Capabilities
- Transport Agnostic: Supports both local Process Communication (STDIO) and remote HTTP streaming interfaces, with automatic fallback mechanisms.
- Decoupled Design: Strict 5-tier separation: Command Line Interface (CLI), Tool Definitions, Orchestration Controllers, Business Service Adapters, and Shared Utilities.
- Data Integrity: Fully typed using TypeScript, with Zod schemas enforcing strict validation on all inputs and outputs.
- Out-of-the-Box Example: Full implementation of an IP geolocation utility, covering all architectural facets.
- Quality Assurance: Includes boilerplate for unit/integration testing frameworks and continuous integration tooling.
- DevOps Ready: Pre-configured for modern practices: ESLint, Prettier, automated semantic versioning, and integration with MCP Inspector for visualization.
- Observability: Structured exception management integrated with contextual, source-aware logging.
Understanding MCP
Model Context Protocol (MCP) standardizes the secure handshake and invocation mechanism between generative AI models and external systems. This boilerplate adheres strictly to the MCP specification, providing a highly extensible structure suitable for connecting AI to any custom backend system or data source.
System Requirements
- Runtime Environment: Node.js (version 18.x or newer): Acquire Here
- Version Control: Git (Required for cloning and development workflow)
Expedited Startup Guide
bash
Clone the repository structure
git clone https://github.com/aashari/boilerplate-mcp-server.git cd boilerplate-mcp-server
Install all necessary dependencies
npm install
Compile source code into distributable JavaScript
npm run build
Execute in various operational modes:
1. Direct CLI Execution - For direct verification/testing
npm run cli -- get-ip-details 8.8.8.8 npm run cli -- get-ip-details # Resolves caller's public address npm run cli -- get-ip-details 1.1.1.1 --include-extended-data
2. Local AI Interaction (STDIO Transport) - For desktop tools like Cursor/Claude
npm run mcp:stdio
3. Networked Integration (HTTP Transport)
npm run mcp:http
4. Interactive Debugging Session
npm run mcp:inspect # Launches server and opens the debugging UI automatically
Supported Communication Transports
Standard Input/Output (STDIO) Transport
- Utilizes JSON-RPC over standard input and output streams.
- Primary transport for tightly coupled, local AI environments (e.g., Cursor, specialized desktop clients).
- Execution Command:
TRANSPORT_MODE=stdio node dist/index.js
Streamable HTTP Transport
- Employs HTTP with Server-Sent Events (SSE) for push capabilities.
- Enables concurrent connections and web-based client integration.
- Default Listening Port: 3000 (Adjustable via the
PORTenvironment variable). - MCP Entry Point:
http://localhost:3000/mcp - Health Check Endpoint:
http://localhost:3000/(Returns server version identifier). - Execution Command:
TRANSPORT_MODE=http node dist/index.js
Architectural Blueprint
Detailed Project Directory Map (Expand for Structure)
src/ ├── cli/ # Command-line execution scripts │ ├── index.ts # CLI bootstrap (Commander setup) │ └── ipaddress.cli.ts # Specific commands for IP address utilities ├── controllers/ # Business orchestration layer │ ├── ipaddress.controller.ts # Logic for IP data orchestration │ └── ipaddress.formatter.ts # Logic for structuring output presentation ├── services/ # External API abstraction layer │ ├── vendor.ip-api.com.service.ts # Adapter for ip-api.com integration │ └── vendor.ip-api.com.types.ts # TypeScript definitions for service contracts ├── tools/ # AI-facing MCP Tool definitions │ ├── ipaddress.tool.ts # Definition for the IP lookup tool │ └── ipaddress.types.ts # Argument schemas (Zod) for tools ├── resources/ # MCP Resource handlers (URI resolution) │ └── ipaddress.resource.ts # Handler for 'ip://...' URIs ├── types/ # Global, shared type definitions │ └── common.types.ts # Core interfaces (e.g., ControllerResponse) ├── utils/ # Reusable, isolated helper functions │ ├── logger.util.ts # Context-aware logging framework │ ├── error.util.ts # MCP-compliant error serialization │ ├── error-handler.util.ts # Utility for error handling across layers │ ├── config.util.ts # Environment variable loading and management │ ├── constants.util.ts # Static application constants (e.g., version) │ ├── formatter.util.ts # Markdown presentation helpers │ └── transport.util.ts # Low-level HTTP client wrappers └── index.ts # Server initialization and dual-transport dispatcherThe 5-Tier Architectural Philosophy
This boilerplate enforces a strict separation of concerns across five primary layers to maximize modularity:
Tier 1: CLI Layer (src/cli/)
- Role: Provides direct, synchronous interaction with the system's capabilities via the terminal.
- Mechanism: Utilizes Commander for declarative argument parsing.
- Workflow: Command registration → Argument parsing → Delegate execution to Controllers → Manage CLI-specific error presentation.
Tier 2: Tools Layer (src/tools/)
- Role: The external-facing interface defined by the MCP standard, designed for AI invocation.
- Mechanism: Defines methods using Zod for precise input validation.
- Example: The
ip_get_detailsfunction, which safely routes validated arguments to the controller.
Tier 3: Resources Layer (src/resources/)
- Role: Handles data exposure via URI schemes (e.g.,
ip://...), as defined in MCP. - Mechanism: Custom handlers that resolve specific URIs into meaningful data payloads.
Tier 4: Controllers Layer (src/controllers/)
- Role: The core business logic orchestrator. Responsible for policy enforcement, input sanitization, and sequencing service calls.
- Mechanism: Manages fallback strategies (e.g., protocol switching) and ensures responses are correctly structured before passing to tools/resources.
Tier 5: Services Layer (src/services/)
- Role: Lowest layer, responsible solely for communicating with external data providers (e.g., REST API calls).
- Mechanism: Contains minimal logic; focuses on HTTP request construction, authentication, and raw data deserialization.
Tier 6: Utilities Layer (src/utils/)
- Role: Houses cross-cutting concerns and shared, stateless functions.
- Key Utilities: Centralized logging tagged with file/method context, robust MCP error serialization, configuration loading, and HTTP request utilities.
Developer Workflow Guide
Essential Development Commands
bash
Core Compilation & Cleanup
npm run build # Transpile TS to JS in dist/ npm run clean # Erase dist/ and coverage reports npm run prepare # Execute build + permission setup (for publishing)
Interactive Testing
npm run cli -- get-ip-details 8.8.8.8 # Execute specific CLI function npm run mcp:stdio # Start server using local pipes npm run mcp:http # Start server via HTTP endpoint npm run mcp:inspect # HTTP server launch with automatic Inspector UI opening
Debugging & Quality Control
npm run dev:stdio # Run STDIO transport with enhanced debugging npm run lint # Static analysis checks (ESLint) npm run format # Code style enforcement (Prettier)
Configuration Environment Variables
Primary Server Settings
TRANSPORT_MODE: Specifies initialization protocol (stdioorhttp). Default isstdio.PORT: The network port to bind the HTTP listener on. Default is3000.DEBUG: Flag to enable verbose logging output (true|false). Default isfalse.
IP API Specifics
IPAPI_API_TOKEN: Required credential for accessing enhanced data tiers on ip-api.com.
Example Environment Setup (.env)
bash TRANSPORT_MODE=http PORT=3002 DEBUG=true IPAPI_API_TOKEN=xyz-123-abc
Debugging Aids
- MCP Inspector: A web-based visualization utility for live-testing tool invocation and inspecting protocol payloads. Activate via
npm run mcp:inspect. - Debug Flag: Set
DEBUG=trueenvironment variable to activate detailed internal logging across all layers.
Global Configuration Override (System-Wide Defaults)
Configuration can be set globally in `~/.mcp/configs.json`: { "boilerplate": { "environments": { "DEBUG": "true", "TRANSPORT_MODE": "http", "PORT": "3000" } } }Guide: Integrating a New Custom Tool
Follow these steps to introduce a new capability, connecting an AI agent to a hypothetical "Inventory API":
Step 1: Service Adapter (src/services/vendor.inventory.service.ts)
Create the lowest-level interaction module. This service only knows how to talk to the external REST endpoint.
typescript // src/services/vendor.inventory.service.ts import { fetchApi } from '../utils/transport.util.js'; // ... imports for types and logging
async function checkStock(itemId: string): Promise<{ count: number, location: string }> {
const url = https://inventory.corp.com/v1/stock/${itemId};
// Use fetchApi for standardized request handling (retries, error wrapping)
const rawData = await fetchApi<{ stock_level: number, warehouse: string }>(url);
// Transform external response to internal standard
return {
count: rawData.stock_level,
location: rawData.warehouse
};
}
export default { checkStock };
Step 2: Controller Orchestrator (src/controllers/inventory.controller.ts)
This layer applies business rules, validates inputs beyond schema, and handles exceptions from the service layer.
typescript // src/controllers/inventory.controller.ts import inventoryService from '../services/vendor.inventory.service.js'; import { handleControllerError, buildErrorContext } from '../utils/error-handler.util.js';
async function resolveStockStatus(itemId: string): PromiseInvalid Item ID format provided: ${itemId});
}
try {
const stockData = await inventoryService.checkStock(itemId);
// Format result into something useful for the AI
if (stockData.count > 0) {
return `Item ${itemId} is available with ${stockData.count} units at ${stockData.location}.`;
} else {
return `Item ${itemId} is currently out of stock.`;
}
} catch (error) {
throw handleControllerError(
error,
buildErrorContext('InventoryLookup', 'resolveStockStatus', 'controllers/inventory.controller.ts', itemId, {})
);
}
}
export default { resolveStockStatus };
Step 3: MCP Tool Definition (src/tools/inventory.tool.ts)
Define the tool interface, Zod schema, and the handler that bridges the Tool Layer to the Controller Layer.
typescript // src/tools/inventory.tool.ts import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; import { z } from 'zod'; import inventoryController from '../controllers/inventory.controller.js'; import { formatErrorForMcpTool } from '../utils/error.util.js';
// Define Schema: Requires a product identifier const StockQuerySchema = z.object({ itemId: z.string().length(8, 'Item ID must be exactly 8 characters.') });
async function executeStockQuery(args: Record
try {
const validatedArgs = StockQuerySchema.parse(args);
// Invoke Controller
const statusMessage = await inventoryController.resolveStockStatus(validatedArgs.itemId);
// Format as MCP tool output
return { content: [{ type: 'markdown' as const, text: statusMessage }] };
} catch (error) {
return formatErrorForMcpTool(error);
}
}
// Registration Function function registerTools(server: McpServer) { server.tool( 'inventory_check_stock', 'Retrieves the current stock level and warehouse location for a given item ID.', StockQuerySchema.shape, executeStockQuery ); }
export default { registerTools };
Step 4: Component Registration
A. Register CLI Interface (src/cli/index.ts): Add a new command mapping to the main CLI entry point.
B. Register Tool (src/index.ts): Integrate the new tool definition into the main server startup sequence.
typescript // Inside server initialization logic in src/index.ts import inventoryTools from './tools/inventory.tool.js'; // ... inventoryTools.registerTools(serverInstance);
Reference Example: IP Geolocation Deep Dive
This built-in example showcases the full stack implementation:
CLI Usage Examples: bash npm run cli -- get-ip-details # For local machine address npm run cli -- get-ip-details 203.0.113.45 # Specific IP query npm run cli -- get-ip-details 1.1.1.1 --include-extended-data # Requesting enriched data
MCP Tool Exposure:
- Tool Name: ip_get_details
- Resource URI: ip://[address]
Key Architectural Demonstrations:
1. Protocol Fallback: If HTTPS request fails (e.g., due to rate limiting or IP range restrictions), the controller automatically retries using plain HTTP.
2. Contextual Data: Usage of environment variables (IPAPI_API_TOKEN) for feature unlocking.
3. Error Context: Reserved IP addresses generate structured MCP errors instead of generic HTTP failures.
Final Deployment Checklist
- Configuration Polish: Update
package.jsonmetadata (name, description, keywords). - Documentation Review: Tailor all README examples to your specific business domain (replace IP lookups).
-
Integrity Check: Verify compilation and run the complete test suite: bash npm run build && npm test
-
Publish: Once validated, use
npm publish(ensure you are logged into the correct npm account).
License Agreement
This software is provided under the permissive ISC License.
External References and Standards
MCP Standard Documentation
- Official MCP Specification
- Model Context Protocol SDK Repository
- MCP Inspector Tool (Debugging Visualization)
Foundational Context (Cloud Computing Overview)
WIKIPEDIA: Cloud computing is "a paradigm for enabling network access to a scalable and elastic pool of shareable physical or virtual resources with self-service provisioning and administration on-demand," according to ISO. It is commonly referred to as "the cloud".
== Core NIST Characteristics == Cloud systems are fundamentally defined by five characteristics established by NIST:
- On-demand self-service: Consumers provision resources without provider intervention.
- Broad network access: Capabilities are available via standard mechanisms accessible by diverse client platforms.
- Resource pooling: Provider infrastructure is shared via a multi-tenant model, dynamically allocated based on demand.
- Rapid elasticity: Resources scale outward and inward near-instantaneously, appearing unlimited to the user.
- Measured service: Resource consumption (processing, storage, bandwidth) is automatically metered, reported, and optimized for transparency.
== Historical Roots == The conceptual foundation traces back to 1960s time-sharing systems and Remote Job Entry (RJE) on mainframes. The visual "cloud" metaphor for network abstraction was adopted in 1994 by General Magic for their Telescript agents, later gaining widespread adoption in computing discussions around 1996.
