Skip to main content
Glama
cameronsjo

MCP Server Template

by cameronsjo

MCP Server Template

A production-ready template for building Model Context Protocol (MCP) servers with TypeScript.

Features

  • MCP SDK 1.24.3 - Latest SDK with 2025-11-25 spec support

  • Dual Transport - Stdio (Claude Desktop) and HTTP (cloud deployment)

  • OAuth 2.1 Foundations - Protected resource metadata, bearer token structure

  • SQLite Caching - TTL-based caching with sql.js (WebAssembly)

  • Observability - Sentry error tracking + OpenTelemetry tracing

  • Security - PII sanitization, rate limiting, DNS rebinding protection

  • Type Safety - Strict TypeScript with Zod validation

Quick Start

# Clone and install
git clone <this-repo> my-mcp-server
cd my-mcp-server
npm install

# Development mode (hot reload)
npm run dev

# Build and run
npm run build
npm start

# Test with MCP Inspector
npm run inspector

Project Structure

src/
├── index.ts              # CLI entry point
├── server.ts             # MCP server implementation
├── instrumentation.ts    # Sentry + OpenTelemetry setup
├── config/
│   └── index.ts          # Environment configuration
├── db/
│   ├── database.ts       # SQLite connection (sql.js)
│   └── cache.ts          # TTL-based caching
├── tools/
│   ├── registry.ts       # Tool registration pattern
│   └── examples.ts       # Example tool implementations
├── transport/
│   └── http-transport.ts # HTTP with OAuth foundations
├── shared/
│   ├── logger.ts         # Structured logging
│   ├── errors.ts         # Custom error classes
│   ├── rate-limiter.ts   # Per-source rate limiting
│   ├── pii-sanitizer.ts  # PII detection/removal
│   └── tracing.ts        # OpenTelemetry utilities
└── types/
    └── index.ts          # TypeScript type definitions

Configuration

Environment variables (prefix with MCP_SERVER_):

Variable

Default

Description

MCP_SERVER_NAME

mcp-server-template

Server name

MCP_SERVER_VERSION

0.1.0

Server version

MCP_SERVER_LOG_LEVEL

info

Log level: debug, info, warning, error

MCP_SERVER_DB_PATH

.data/cache.db

SQLite database path

MCP_SERVER_CACHE_ENABLED

true

Enable/disable caching

MCP_SERVER_CACHE_TTL

3600

Default cache TTL (seconds)

MCP_SERVER_TIMEOUT

30000

Request timeout (ms)

MCP_SERVER_TRANSPORT

stdio

Transport: stdio or http

MCP_SERVER_PORT

3000

HTTP port (when transport=http)

MCP_SERVER_HOST

127.0.0.1

HTTP host (when transport=http)

MCP_SERVER_SENTRY_DSN

-

Sentry DSN for error tracking

OTEL_ENABLED

false

Enable OpenTelemetry tracing

OTEL_EXPORTER_OTLP_ENDPOINT

-

OTLP collector endpoint

MCP_SERVER_DEBUG

false

Debug mode (skips auth)

Creating Tools

Tools are registered with the ToolRegistry using Zod schemas:

import { z } from 'zod';
import { getToolRegistry } from './tools/registry.js';

// Define input schema
const MyToolInputSchema = z.object({
  query: z.string().min(1).describe('Search query'),
  limit: z.number().positive().optional().default(10),
});

type MyToolInput = z.infer<typeof MyToolInputSchema>;

// Implement handler
async function myToolHandler(input: MyToolInput) {
  // Your implementation here
  return {
    success: true,
    data: { results: [] },
  };
}

// Register tool
const registry = getToolRegistry();
registry.register(
  'my_tool',
  'Description of what this tool does',
  MyToolInputSchema,
  myToolHandler
);

Transport Modes

Stdio (Default)

For Claude Desktop and local integrations:

npm start

Add to Claude Desktop config:

{
  "mcpServers": {
    "my-server": {
      "command": "node",
      "args": ["/path/to/dist/index.js"]
    }
  }
}

HTTP

For cloud deployment:

MCP_SERVER_TRANSPORT=http npm start

Endpoints:

  • GET /health - Health check

  • GET /.well-known/mcp - MCP server metadata

  • GET /.well-known/oauth-protected-resource - OAuth metadata (RFC 9728)

  • GET /mcp - SSE stream for server events

  • POST /mcp - JSON-RPC requests

  • DELETE /mcp - Close session

Security Features

PII Sanitization

Automatically detects and masks sensitive data:

import { sanitizePii } from './shared/pii-sanitizer.js';

const safe = sanitizePii('Contact: user@example.com');
// Output: "Contact: [EMAIL]"

Rate Limiting

Per-source rate limiting with exponential backoff:

import { getRateLimiter } from './shared/rate-limiter.js';

const limiter = getRateLimiter();
limiter.configure('external-api', {
  requestsPerWindow: 100,
  windowMs: 60000,
});

await limiter.waitForSlot('external-api');
// Make request...

DNS Rebinding Protection

HTTP transport validates Host headers against allowlist.

Observability

Sentry

Error tracking with PII filtering:

MCP_SERVER_SENTRY_DSN=https://xxx@sentry.io/xxx npm start

OpenTelemetry

Distributed tracing:

OTEL_ENABLED=true \
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 \
npm start

Use tracing utilities:

import { withSpan, createApiSpan } from './shared/tracing.js';

const result = await withSpan('my-operation', async (span) => {
  span.setAttribute('custom.attr', 'value');
  return doWork();
});

Development

# Type check
npm run check

# Lint
npm run lint
npm run lint:fix

# Format
npm run format

# Test
npm test
npm run test:coverage

# Validate (all checks)
npm run validate

MCP 2025-11-25 Spec Compliance

Feature

Status

Tools

✅ Implemented

Resources

📝 Scaffolded

Prompts

📝 Scaffolded

Streamable HTTP

✅ Implemented

.well-known/mcp

✅ Implemented

OAuth 2.1 Foundations

✅ Scaffolded

Tasks

❌ Not yet

Elicitation

❌ Not yet

OAuth 2.1 Implementation

The template includes foundations for OAuth 2.1 per the MCP spec:

  1. Protected Resource Metadata (RFC 9728) at /.well-known/oauth-protected-resource

  2. Bearer token middleware structure (implement JWT validation)

  3. WWW-Authenticate headers with resource_metadata reference

  4. Scope checking structure for tool authorization

To complete OAuth integration:

  1. Choose an authorization server (Auth0, Logto, etc.)

  2. Implement JWT validation in bearerAuthMiddleware

  3. Add JWKS fetching and caching

  4. Configure scopes per tool

See MCP Authorization Spec for details.

License

MIT

References

Available Tools

4 tools
addB

Add two numbers together

ParametersJSON Schema
NameRequiredDescriptionDefault
aYesFirst number
bYesSecond number

TDQS

B3.3/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It states the action ('add two numbers together') but does not cover important traits like error handling (e.g., for non-numeric inputs), performance characteristics, or output format. This leaves gaps in understanding how the tool behaves beyond its basic function.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that directly states the tool's purpose without any wasted words. It is front-loaded and appropriately sized for a simple arithmetic tool, making it easy to understand at a glance.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's low complexity (basic addition with two parameters) and no output schema, the description is minimally complete. It covers the core action but lacks details on return values or behavioral nuances. Without annotations, it should ideally mention the output type or error cases to be fully comprehensive.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema has 100% description coverage, with parameters 'a' and 'b' clearly documented as 'First number' and 'Second number'. The description adds no additional meaning beyond what the schema provides, such as constraints or examples. With high schema coverage, the baseline score of 3 is appropriate.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description 'Add two numbers together' clearly states the specific verb ('add') and resource ('two numbers'), making the purpose unambiguous. It distinguishes itself from sibling tools like 'cache', 'echo', and 'status' by focusing on arithmetic addition rather than data storage, repetition, or system status.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It does not mention any specific contexts, prerequisites, or exclusions, nor does it compare to other tools for mathematical operations. Usage is implied solely by the tool's name and description.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

cacheB

Get or set a cached value. Provide only key to get, provide key and value to set.

ParametersJSON Schema
NameRequiredDescriptionDefault
keyYesKey to fetch or store
valueNo
ttlSecondsNo

TDQS

B3.4/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden. It mentions the basic behavior (get or set) but lacks details on permissions, rate limits, error handling, or what happens on set (e.g., overwriting). For a mutation tool with zero annotation coverage, this is insufficient, leaving gaps in understanding its operational traits.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is two sentences, front-loaded with the purpose and followed by usage rules. Every word earns its place with no redundancy or fluff, making it highly efficient and easy to parse.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool has 3 parameters with low schema coverage (33%), no annotations, and no output schema, the description is incomplete. It covers basic usage but misses details on 'ttlSeconds', return values, error conditions, and behavioral aspects like concurrency or persistence, which are critical for a caching tool.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 33% (only 'key' has a description), and the description adds value by explaining that 'key' is used for both get and set operations and 'value' is needed for set. However, it doesn't cover 'ttlSeconds' at all, and with low schema coverage, the description only partially compensates, leaving one parameter undocumented.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose as 'Get or set a cached value,' which is a specific verb+resource combination. However, it doesn't distinguish this tool from its siblings (add, echo, status), which appear unrelated to caching operations, so differentiation isn't necessary but the purpose remains clear without it.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides explicit guidance on when to use the tool: 'Provide only key to get, provide key and value to set.' This clarifies the conditional usage based on parameters. However, it doesn't mention when not to use it or alternatives, and the sibling tools seem unrelated, so no explicit exclusions are needed.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

echoC

Echo a message back, optionally in uppercase

ParametersJSON Schema
NameRequiredDescriptionDefault
messageYesThe message to echo back
uppercaseNo

TDQS

C2.9/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It states the tool echoes a message back with an optional uppercase transformation, but it doesn't cover other behavioral traits such as whether it's read-only or destructive, any rate limits, error handling, or authentication needs. This leaves significant gaps in understanding how the tool behaves beyond its basic function.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is extremely concise and front-loaded: 'Echo a message back, optionally in uppercase.' It uses a single sentence that efficiently conveys the core functionality without any wasted words, making it easy to understand at a glance.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's low complexity and lack of annotations or output schema, the description is incomplete. It covers the basic purpose but misses key contextual details such as behavioral traits, usage guidelines, and fuller parameter explanations. For a tool with no structured support, the description should do more to compensate, but it falls short.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema description coverage is 50% (only 'message' has a description, 'uppercase' does not). The description adds minimal value by mentioning 'optionally in uppercase,' which hints at the 'uppercase' parameter's purpose but doesn't provide detailed semantics like default behavior or effects. Since schema coverage is moderate, the baseline is 3, and the description only slightly compensates for the gap.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Echo a message back, optionally in uppercase.' It specifies the verb ('echo') and resource ('message'), and the optional uppercase transformation adds specificity. However, it doesn't differentiate from sibling tools like 'add', 'cache', or 'status', which likely have different functions, so it doesn't fully achieve sibling differentiation.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It mentions the optional uppercase feature but doesn't explain scenarios where this tool is appropriate compared to siblings like 'add' or 'cache', nor does it specify any prerequisites or exclusions for usage.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

statusB

Get server status and cache statistics

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

TDQS

B3.1/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. While 'Get' implies a read-only operation, it doesn't specify whether this requires permissions, what data is returned (e.g., uptime, memory usage), or if it has side effects like resetting statistics. The description is too vague for a tool with no annotation coverage.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that directly states the tool's function without unnecessary words. It is appropriately sized and front-loaded, making it easy to understand at a glance.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the lack of annotations and output schema, the description is incomplete. It doesn't explain what 'server status' or 'cache statistics' entail, the format of the return data, or any behavioral nuances. For a tool with no structured data support, this leaves significant gaps for an AI agent.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema has 0 parameters with 100% coverage, so the schema fully documents the lack of inputs. The description adds no parameter information, which is acceptable since there are no parameters to describe, earning a baseline score of 4 for this context.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose with a specific verb ('Get') and resources ('server status and cache statistics'). It distinguishes this as a read operation for system information, though it doesn't explicitly differentiate from sibling tools like 'cache' which might also relate to cache operations.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives like 'cache' or 'echo'. It lacks context about scenarios where checking server status or cache statistics is appropriate, such as monitoring health or troubleshooting performance issues.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections. Dates show when Glama detected each change.

  1. 4 tool updates
    • First observedadd
    • First observedcache
    • First observedecho
    • First observedstatus

TDQS

A3.5/5.0
Disambiguation5/5

Each tool has a clearly distinct purpose: add performs arithmetic, cache handles key-value storage, echo returns input with optional transformation, and status provides server metadata. There is no overlap or ambiguity between these functions.

Naming Consistency5/5

All tool names follow a consistent, simple verb-based pattern (add, cache, echo, status) without mixing conventions like snake_case or camelCase. This uniformity makes the set predictable and easy to understand.

Tool Count4/5

With 4 tools, the count is reasonable for a template server, covering basic utilities like arithmetic, caching, echoing, and status checks. It's slightly minimal but well-scoped for demonstration purposes, lacking only minor expansions.

Completeness3/5

As a template server, it covers fundamental operations but has notable gaps for a more robust utility set, such as missing tools for deletion, advanced caching operations, or error handling. However, it provides a complete basic workflow for its intended scope.

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/cameronsjo/mcp-server-template'

If you have feedback or need assistance with the MCP directory API, please join our Discord server