mcp-context-adapter-scaffold
A robust TypeScript template for constructing bespoke Model Context Protocol (MCP) bridging entities. This scaffold facilitates secure linkage between sophisticated artificial intelligence agents and external data repositories or remote service APIs, ensuring fluid data exchange and retrieval capabilities. It incorporates native utility modules for network address inspection and command-line interface provisioning to streamline deployment workflows.
Author

aashari
Quick Info
Actions
Tags
MCP Context Bridge Foundation
This artifact serves as a production-grade baseline for architecting custom Model Context Protocol (MCP) intermediary servers utilizing TypeScript. It mandates a strictly layered architectural paradigm, furnishes fully operational usage examples, and equips developers with the requisite infrastructure to seamlessly connect cognitive AI systems to heterogeneous data sources and operational APIs.
Core Capabilities
- Dual Channel Communication: Supports synchronous Inter-Process Communication (STDIO) alongside streamable HyperText Transfer Protocol (HTTP) channels, featuring automatic fallback mechanisms.
- Five-Tiered Structure: Enforces rigorous separation of concerns across the CLI, Tooling, Control, Service, and Utility modules.
- Compile-Time Integrity: Fully implemented in TypeScript, leveraging Zod for precise data schema validation.
- Geolocation Blueprint: Includes complete functional tooling, assets, and CLI invocation sequences for inspecting network addresses (IPs).
- Quality Assurance Suite: Comprehensive unit and end-to-end verification routines with automated coverage reports.
- Production Readiness: Integrated linting (ESLint), formatting (Prettier), automated version control (semantic-release), and MCP Inspector compatibility.
- Systematic Failure Management: Structured exception handling paired with context-aware logging mechanisms.
Understanding the MCP Framework
Model Context Protocol (MCP) defines an open, secure specification for enabling artificial general intelligence constructs to interact with auxiliary apparatus and external knowledge bases. This foundational template meticulously adheres to the MCP specification, presenting a highly modular, layered structure ready for specialization into unique MCP gateways for any designated API or data silo.
Prerequisites for Operation
- Node Runtime Environment (Minimum version 18.x): Acquire Here
- Version Control System: Git is required for source management.
Expedited Initialization
bash
Clone the repository source
git clone https://github.com/aashari/boilerplate-mcp-server.git cd boilerplate-mcp-server
Install required dependencies
npm install
Compile the source code
npm run build
Execute in various operational modalities:
1. Command-Line Interface Mode - Direct tool execution
npm run cli -- get-ip-details 8.8.8.8 npm run cli -- get-ip-details # Determine host's current network identifier npm run cli -- get-ip-details 1.1.1.1 --include-extended-data
2. STDIO Transport - Optimized for local AI environments (e.g., Cursor, Claude Desktop)
npm run mcp:stdio
3. HTTP Transport - For web service integrations
npm run mcp:http
4. Development with Integrated Debugger (MCP Inspector)
npm run mcp:inspect # Launches server and opens debugging UI automatically
Communication Transports
STDIO Channel
- Leverages JSON-RPC protocol over standard input/output streams.
- Primary use case: Integration with local AI desktop environments.
- Execution command:
TRANSPORT_MODE=stdio node dist/index.js
Streamable HTTP Channel
- Employs HTTP transport utilizing Server-Sent Events (SSE) for persistent data flow.
- Supports concurrent client connections; ideal for web-based conduits.
- Listens on TCP port 3000 by default (adjustable via
PORTenvironment variable). - MCP Access Point:
http://localhost:3000/mcp - Status Endpoint:
http://localhost:3000/→ Returns operational server revision. - Execution command:
TRANSPORT_MODE=http node dist/index.js
Architectural Blueprint Summary
Source Code Organization (Expand View)
src/ ├── cli/ # Command-line interface definitions │ ├── index.ts # CLI entry point utilizing Commander framework │ └── ipaddress.cli.ts # Specific commands related to IP lookup ├── controllers/ # Business logic orchestration nexus │ ├── ipaddress.controller.ts # Core logic for IP address resolution │ └── ipaddress.formatter.ts # Output structuring utilities ├── services/ # External remote API interaction handlers │ ├── vendor.ip-api.com.service.ts # Logic interacting with ip-api.com │ └── vendor.ip-api.com.types.ts # Type definitions for external service data ├── tools/ # MCP tool definitions (AI-facing interfaces) │ ├── ipaddress.tool.ts # The defined IP geolocation tool │ └── ipaddress.types.ts # Schemas for tool arguments ├── resources/ # MCP resource definitions (URI-addressable data) │ └── ipaddress.resource.ts # Resource handler for IP data (URI: ip://address) ├── types/ # Global type definitions │ └── common.types.ts # Shared interfaces (e.g., ControllerResponse) ├── utils/ # Reusable shared components │ ├── logger.util.ts # Contextual, layered logging facility │ ├── error.util.ts # MCP-specific error serialization │ ├── error-handler.util.ts # General error management utilities │ ├── config.util.ts # Environment variable acquisition │ ├── constants.util.ts # Versioning and static package values │ ├── formatter.util.ts # Markdown rendering helpers │ └── transport.util.ts # HTTP transport mechanisms └── index.ts # Primary application bootstrap (dual transport initiation)Dissecting the Five-Tiered Software Structure
The scaffold adheres to a rigid, layered pattern designed to maximize code clarity and diminish functional overlap:
Tier 1: Command-Line Interface (src/cli/)
- Goal: Provision interfaces for direct invocation and diagnostic testing.
- Mechanism: Commander-based argument parsing coupled with contextual error propagation.
- Usage Example:
get-ip-details [address] --include-extended-data --no-use-https - Workflow: Command Registration → Argument Parsing → Controller Invocation → Error Management
Tier 2: Tool Definitions (src/tools/)
- Goal: Define the explicit functions consumable by AI agents via MCP.
- Mechanism: Utilization of Zod schemas for strict input validation, ensuring structured output.
- Usage Example: The
ip_get_detailsprimitive supporting optional IP input and configuration flags. - Workflow: Schema Declaration → Argument Validation → Controller Delegation → MCP Response Formatting
Tier 3: Resource Definitions (src/resources/)
- Goal: Offer contextually rich data accessible via Uniform Resource Identifiers (URIs).
- Mechanism: Specialized handlers responding to URI pattern matches.
- Usage Example: Fetching details via the
ip://8.8.8.8endpoint. - Workflow: URI Pattern Registration → Request Deconstruction → Content Serialization
Tier 4: Control Logic (src/controllers/)
- Goal: Central hub for business process orchestration and comprehensive failure intercepts.
- Mechanism: Input parameter validation, application of default settings, fallback contingency planning, and output transformation.
- Usage Example: IP lookup featuring HTTPS preference with an HTTP fallback, environment checks, and API key verification.
- Workflow: Input Validation → Default Application → Service Invocation → Response Structuring
Tier 5: External Interaction Services (src/services/)
- Goal: Direct, low-level communication with external web endpoints; minimal domain logic resides here.
- Mechanism: HTTP transport utilities configured with built-in error serialization.
- Usage Example: Performing authenticated calls to the ip-api.com endpoint, including field selection.
- Workflow: Request Construction → Remote API Invocation → Response Integrity Check → Raw Data Return
Utility Layer (src/utils/)
- Goal: Share common functional blocks across all application tiers.
- Key Facilitators:
logger.util.ts: Enables context-specific logging (e.g., tracking file/method execution path).error.util.ts: Serializes exceptions into the mandated MCP error format.transport.util.ts: HTTP client abstraction, supporting retry logic.config.util.ts: Centralized management of runtime configuration parameters.
Developer Lifecycle Guide
Scripted Operations
bash
Codebase Compilation & Cleanup
npm run build # Transpile TypeScript source to JavaScript output directory (dist/) npm run clean # Obliterate dist/ and coverage/ directories npm run prepare # Build cycle followed by setting executable permissions (for registry upload)
Command-Line Utility Verification
npm run cli -- get-ip-details 8.8.8.8 # Test resolution for a hardcoded IP npm run cli -- get-ip-details --include-extended-data # Test with supplementary data request npm run cli -- get-ip-details --no-use-https # Force non-secure HTTP transmission
MCP Endpoint Modes
npm run mcp:stdio # Activate STDIO conduit for AI clients npm run mcp:http # Activate HTTP conduit on default port npm run mcp:inspect # Activate HTTP conduit with automatic MCP Inspector launch
Interactive Debugging Sessions
npm run dev:stdio # STDIO mode paired with Inspector connection npm run dev:http # HTTP mode with verbose debug tracing enabled
Quality Assurance
npm test # Execute all defined test suites (Jest) npm run test:coverage # Generate a comprehensive test coverage artifact npm run test:cli # Execute tests strictly limited to CLI components
Code Style Enforcement
npm run lint # Run ESLint static analysis against TypeScript npm run format # Apply code formatting standards via Prettier npm run update:deps # Script for dependency version refreshment
Environment Variable Configuration
Primary Controls
TRANSPORT_MODE: Specifies communication protocol (stdio|http, defaults tostdio)PORT: TCP port number for HTTP endpoint binding (defaults to3000)DEBUG: Toggles verbose logging (true|false, defaults tofalse)
IP Geolocation API Specifics
IPAPI_API_TOKEN: Authentication key for ip-api.com services requiring premium feature access (optional).
Example Runtime Configuration (.env)
bash
General operational setup
TRANSPORT_MODE=http PORT=3001 DEBUG=true
Credential requirement for enhanced data fetching
IPAPI_API_TOKEN=your_secret_key_here
Debugging Instrumentation
- MCP Inspector: A graphical utility designed for interactive validation of MCP tool operations.
- Initiate via:
npm run mcp:inspect - Access the displayed URL in a web browser.
-
Systematically test all defined tool interfaces.
-
Diagnostic Logging: Activated globally by setting the
DEBUG=trueenvironment flag.
Global Configuration Override (Click to expand)
Configuration can be persisted globally by generating or modifying `~/.mcp/configs.json`: { "boilerplate": { "environments": { "DEBUG": "true", "TRANSPORT_MODE": "http", "PORT": "3000" } } }Constructing Novel Tooling Extensions
Methodical Guide for Tool Implementation (Expand for Steps)
### Phase 1: Establish the Service Interface Develop a dedicated service module within `src/services/` using vendor-specific nomenclature: typescript // src/services/vendor.example-api.service.ts import { Logger } from '../utils/logger.util.js'; import { fetchApi } from '../utils/transport.util.js'; import { ExampleApiResponse, ExampleApiRequestOptions } from './vendor.example-api.types.js'; import { createApiError, McpError } from '../utils/error.util.js'; const serviceLogger = Logger.forContext('services/vendor.example-api.service.ts'); async function get( param?: string, options: ExampleApiRequestOptions = {} ): PromiseIP Address Reference Implementation Details
The bundled IP geolocation mechanism showcases the full stack integration:
Operational Access Points
Command Line Invocation: bash npm run cli -- get-ip-details # Resolve host's public IP npm run cli -- get-ip-details 8.8.8.8 # Resolve specific IP details npm run cli -- get-ip-details 1.1.1.1 --include-extended-data # Requesting comprehensive metadata npm run cli -- get-ip-details 8.8.8.8 --no-use-https # Mandate non-secure HTTP transport
MCP Interface Invocation:
- Tool: ip_get_details - Used by intelligent agents for geographical lookups.
- Resource: ip:// (self) and ip://8.8.8.8 (specific address) endpoints.
Demonstrated Architectural Features
- Transport Contingency: Automatic switch from secure HTTPS requests to standard HTTP if necessary (common for rate-limited free tiers).
- Runtime Context Awareness: Different execution paths are triggered based on whether the process is running in a testing harness versus a live production or development mode.
- Secret Management: Optional token integration for services like ip-api.com to unlock richer telemetry (e.g., ASN, ISP identification).
- Resilient Error Reporting: Structured failure modes for addresses classified as private or reserved.
- Output Formatting: Consistent delivery of geolocation results rendered cleanly in Markdown format.
Environmental Parameters
bash
Optional: To unlock premium geolocation attributes
IPAPI_API_TOKEN=your_token_from_ip-api.com
Debugging and Transport Selection
DEBUG=true # Activate verbose logging for tracing TRANSPORT_MODE=http # Specify HTTP communication conduit PORT=3001 # Assign alternative port number
Artifact Deployment Procedure
- Package Metadata Customization:
{ "name": "your-custom-mcp-gateway", "version": "1.0.0", "description": "My specialized MCP integration server", "author": "Your Identifier", "keywords": ["mcp", "custom-api", "ai-connector"] }
- Documentation Update: Substitute the default IP address content with your specific use-case documentation.
-
Verification Phase: bash npm run build && npm test npm run cli -- your-tool-name npm run mcp:stdio # Validate functionality using the Inspector tool
-
Public Release: Execute
npm publish(requires priornpm login).
Verification Framework Philosophy
The provided system includes an embedded, comprehensive testing infrastructure:
Test Location Schema
Tests are deliberately co-located with their corresponding source modules:
src/ ├── */.test.ts # Unit/Integration tests adjacent to implementation files ├── utils/ # Tests for foundational utility functions ├── controllers/ # Logic verification tests (service layer is mocked) ├── services/ # Tests focused on external network interaction reliability └── cli/ # Tests verifying command parsing and execution flow
Testing Directives
- Unit Validation: Focus on pure functions and utilities (
*.util.test.ts). - Controller Validation: Verify business process execution; external services must be mocked.
- Service Validation: Confirm correct interaction protocol with external APIs (use mocks for live network calls).
- CLI Validation: Ensure command argument parsing and controller handoff are correct.
- Environment Simulation: Controllers must correctly handle automatic detection of 'test' runtime mode.
Executing Quality Gates
bash npm test # Execute all automated tests suite npm run test:coverage # Generate test coverage statistics npm run test:cli # Run only tests pertaining to command-line interfaces
Coverage Objectives
- Target Threshold: Aim for exceeding 80% code coverage.
- Focus Areas: Prioritize high-coverage in critical business logic (controllers) and core utilities.
Licensing Terms
This software is distributed under the permissive ISC License.
Supporting Documentation and References
Core MCP Protocol Links
- Official MCP Specification Document
- MCP Software Development Kit Repository
- MCP Inspector Project Page - For visual debugging assistance
Implementation Context
- Anthropic's Initial MCP Disclosure
- Curated List of MCP Server Implementations
- Official TypeScript Language Documentation
