logo
Free, unlimited AI code reviews that run on commit
git-lrc git-lrc GitHub Install Now We'd appreciate a star git-lrc - Free, unlimited AI code reviews that run on commit | Product Hunt git-lrc - Free, unlimited AI code reviews that run on commit | Product Hunt

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

mcp-context-adapter-scaffold logo

aashari

No License

Quick Info

GitHub GitHub Stars 57
NPM Weekly Downloads 0
Tools 1
Last Updated 2026-02-19

Tags

apisprotocolmcpmcp servermcp serversprotocol mcp

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.

NPM Version License: ISC

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 PORT environment 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_details primitive 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.8 endpoint.
  • 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 to stdio)
  • PORT: TCP port number for HTTP endpoint binding (defaults to 3000)
  • DEBUG: Toggles verbose logging (true | false, defaults to false)

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=true environment 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 = {} ): Promise { const methodLogger = serviceLogger.forMethod('get'); methodLogger.debug(`Invoking Example API with argument: ${param}`); try { const url = `https://api.example.com/${param || 'default'}`; const rawData = await fetchApi(url, { headers: options.apiKey ? { 'Authorization': `Bearer ${options.apiKey}` } : {} }); methodLogger.debug('Successful data fetch from Example API.'); return rawData; } catch (error) { methodLogger.error('Service layer communication failure', error); if (error instanceof McpError) { throw error; } throw createApiError( 'Unforeseen exception during external data acquisition', undefined, error ); } } export default { get }; ### Phase 2: Construct the Controller Implement business logic orchestration and error context encapsulation in `src/controllers/`: typescript // src/controllers/example.controller.ts import { Logger } from '../utils/logger.util.js'; import exampleService from '../services/vendor.example-api.service.js'; import { formatExample } from './example.formatter.js'; import { handleControllerError, buildErrorContext } from '../utils/error-handler.util.js'; import { ControllerResponse } from '../types/common.types.js'; import { config } from '../utils/config.util.js'; const logger = Logger.forContext('controllers/example.controller.ts'); export interface GetDataOptions { param?: string; includeMetadata?: boolean; } async function getData( options: GetDataOptions = {} ): Promise { const methodLogger = logger.forMethod('getData'); methodLogger.debug(`Initiating data retrieval for parameter: ${options.param || 'default'}`, options); try { // Apply domain rules and default values const apiKey = config.get('EXAMPLE_API_TOKEN'); // Invoke subordinate service layer const data = await exampleService.get(options.param, { apiKey, includeMetadata: options.includeMetadata ?? false }); // Transform data into required output format const formattedContent = formatExample(data); return { content: formattedContent }; } catch (error) { throw handleControllerError( error, buildErrorContext( 'ExampleData', 'getData', 'controllers/example.controller.ts@getData', options.param || 'default', { options } ) ); } } export default { getData }; ### Phase 3: Define the MCP Interface Tool Create the tool manifestation file in `src/tools/`, adhering to the registration pattern: typescript // src/tools/example.tool.ts import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; import { z } from 'zod'; import { Logger } from '../utils/logger.util.js'; import { formatErrorForMcpTool } from '../utils/error.util.js'; import exampleController from '../controllers/example.controller.js'; const logger = Logger.forContext('tools/example.tool.ts'); // Define Zod schema for tool arguments const GetDataSchema = z.object({ param: z.string().optional().describe('Optional parameter for the API call'), includeMetadata: z.boolean().optional().default(false) .describe('Whether to include additional metadata in the response') }); async function handleGetData(args: Record) { const methodLogger = logger.forMethod('handleGetData'); try { methodLogger.debug('Tool example_get_data invoked', args); // Validate arguments using Zod schema const validatedArgs = GetDataSchema.parse(args); // Delegate execution to controller const result = await exampleController.getData({ param: validatedArgs.param, includeMetadata: validatedArgs.includeMetadata }); // Return response conforming to MCP structure return { content: [ { type: 'text' as const, text: result.content } ] }; } catch (error) { methodLogger.error('Tool example_get_data encountered failure', error); return formatErrorForMcpTool(error); } } // Registration function adhering to established system patterns function registerTools(server: McpServer) { const registerLogger = logger.forMethod('registerTools'); registerLogger.debug('Registering example tools...'); server.tool( 'example_get_data', `Retrieves data from the Example API, optionally parameterized.\nInvoke this tool to fetch pertinent example datasets. Output is rendered as Markdown.`, GetDataSchema.shape, handleGetData ); registerLogger.debug('Example tools successfully provisioned.'); } export default { registerTools }; ### Phase 4: Integrate CLI Interaction Establish a new interface within `src/cli/` using the Commander convention: typescript // src/cli/example.cli.ts import { Command } from 'commander'; import { Logger } from '../utils/logger.util.js'; import exampleController from '../controllers/example.controller.js'; import { handleCliError } from '../utils/error.util.js'; const logger = Logger.forContext('cli/example.cli.ts'); function register(program: Command) { const methodLogger = logger.forMethod('register'); methodLogger.debug('Registering example CLI interfaces...'); program .command('get-data') .description('Fetches data from the designated Example API source') .argument('[param]', 'Optional string parameter for the API query') .option('-m, --include-metadata', 'Toggle inclusion of supplementary metadata in the result set') .action(async (param, options) => { const actionLogger = logger.forMethod('action:get-data'); try { actionLogger.debug('CLI get-data execution initiated', { param, options }); const result = await exampleController.getData({ param, includeMetadata: options.includeMetadata || false }); console.log(result.content); } catch (error) { handleCliError(error); } }); methodLogger.debug('Example CLI interfaces provisioned.'); } export default { register }; ### Phase 5: Component Registration Update the primary application manifest files to recognize your new additions: typescript // 1. CLI Initialization in src/cli/index.ts import exampleCli from './example.cli.js'; export async function runCli(args: string[]) { // ... existing setup logic ... // Integrate new CLI commands exampleCli.register(program); // <-- ADDITION // ... remaining function body ... } // 2. Tool Registration in src/index.ts import exampleTools from './tools/example.tool.js'; // Within the main server bootstrapping routine: exampleTools.registerTools(serverInstance);

IP 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

  1. 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"] }

  1. Documentation Update: Substitute the default IP address content with your specific use-case documentation.
  2. Verification Phase: bash npm run build && npm test npm run cli -- your-tool-name npm run mcp:stdio # Validate functionality using the Inspector tool

  3. Public Release: Execute npm publish (requires prior npm 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

Implementation Context

See Also

`