Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

3 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

MCP Server Template with Modular Tools

A Node.js implementation of an MCP (Model Context Protocol) server built on the 2026-07-28 specification: stateless, per-request metadata, Streamable HTTP.

Features

  • MCP 2026-07-28 only: stateless core, server/discover, subscriptions/listen, resultType, cacheable list results, request-metadata headers β€” no handshake-era code paths to maintain
  • Dynamic Tool Loading: automatically discovers and loads tools from /tools
  • Typed tool results: outputSchema + structuredContent, input validation
  • API Key Authentication with an RFC 9728 WWW-Authenticate challenge
  • Sample Tools: calculator and timestamp for demonstration

What changed in 2026-07-28

The 2026-07-28 revision made MCP a stateless request/response protocol. This server implements that revision and nothing older β€” a client on 2025-11-25 or earlier gets a 400 telling it which version to use. If you are pointing an existing client at this server, these are the changes that matter:

Removed Replacement
initialize / notifications/initialized Per-request _meta on every request
Mcp-Session-Id header, DELETE /mcp No protocol sessions β€” pass explicit handles as tool arguments
GET /mcp SSE stream, resources/subscribe subscriptions/listen (one long-lived POST-response stream)
ping, logging/setLevel, notifications/roots/list_changed Removed; log level is per-request via _meta
Last-Event-ID resumability, SSE event ids None β€” re-issue the request with a new id
Server-initiated sampling/createMessage, elicitation/create, roots/list Multi Round-Trip Requests (resultType: "input_required")
JSON-RPC batching One JSON-RPC message per POST

Added: server/discover, the required resultType field on every result, ttlMs/cacheScope on list results, required MCP-Protocol-Version / Mcp-Method / Mcp-Name headers, x-mcp-header tool parameters, and the -32020/-32021/-32022 error codes. Roots, Sampling and Logging are now deprecated and are not advertised by this server.

Quick Start

  1. Install dependencies:
npm install
  1. Set up environment:
cp .env.example .env
  1. Start the server:
npm start
  1. Run the conformance tests:
npm test

Server runs on http://127.0.0.1:3202.

πŸ” Authentication

An API key is required for all requests (except /health):

curl -H "Authorization: Bearer your-api-key" http://127.0.0.1:3202/health

X-API-Key and an ?api_key= query parameter also work, but the Authorization header is what MCP clients send. A 401 carries a WWW-Authenticate: Bearer challenge. Set MCP_AUTHORIZATION_SERVER to advertise a real OAuth 2.0 authorization server β€” the challenge then points at /.well-known/oauth-protected-resource (RFC 9728), which is what MCP clients probe. Client credentials must be keyed by issuer, and new clients should prefer Client ID Metadata Documents over Dynamic Client Registration, which this revision deprecates.

πŸ“‘ Talking to the server

Every request carries its protocol version, client identity and capabilities in params._meta, and mirrors method (and name/uri) into HTTP headers. A mismatch between headers and body is rejected with 400 and error -32020.

Discovery

curl -X POST http://127.0.0.1:3202/mcp -H "Authorization: Bearer your-api-key" -H "Content-Type: application/json" -H "Accept: application/json, text/event-stream" -H "MCP-Protocol-Version: 2026-07-28" -H "Mcp-Method: server/discover" -d '{"jsonrpc":"2.0","id":1,"method":"server/discover","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"curl","version":"1.0.0"},"io.modelcontextprotocol/clientCapabilities":{}}}}'

Calling a tool

tools/call additionally requires the Mcp-Name header, matching params.name:

curl -X POST http://127.0.0.1:3202/mcp -H "Authorization: Bearer your-api-key" -H "Content-Type: application/json" -H "Accept: application/json, text/event-stream" -H "MCP-Protocol-Version: 2026-07-28" -H "Mcp-Method: tools/call" -H "Mcp-Name: calculator" -d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"calculator","arguments":{"operation":"multiply","operand1":7,"operand2":8},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}'

Response:

{
  "jsonrpc": "2.0",
  "id": 2,
  "result": {
    "resultType": "complete",
    "content": [{ "type": "text", "text": "{\"operation\":\"multiply\",\"operands\":[7,8],\"result\":56}" }],
    "structuredContent": { "operation": "multiply", "operands": [7, 8], "result": 56 },
    "_meta": { "io.modelcontextprotocol/serverInfo": { "name": "mcp-server", "version": "2.0.0" } }
  }
}

Add "progressToken" to _meta and send Accept: text/event-stream to get the response as a stream with notifications/progress ahead of the result.

Change notifications

curl -N -X POST http://127.0.0.1:3202/mcp -H "Authorization: Bearer your-api-key" -H "Content-Type: application/json" -H "Accept: text/event-stream" -H "MCP-Protocol-Version: 2026-07-28" -H "Mcp-Method: subscriptions/listen" -d '{"jsonrpc":"2.0","id":1,"method":"subscriptions/listen","params":{"notifications":{"toolsListChanged":true},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}'

The first message is notifications/subscriptions/acknowledged, echoing the filters the server will honour. Every message on the stream is tagged with io.modelcontextprotocol/subscriptionId. Run with MCP_WATCH_TOOLS=true and edit a file in tools/ to see notifications/tools/list_changed arrive.

Closing the stream is the cancellation signal β€” there is no DELETE.

πŸ› οΈ Available Tools

Tool Description
calculator Add, subtract, multiply, divide β€” returns structuredContent
timestamp Current time as ISO 8601, Unix epoch, or human-readable

βš™οΈ Creating Your Tools

1. Tool File Structure

Create tools/your-tool.js:

const TOOL_DEFINITION = {
    name: "your_tool",
    title: "Your Tool",
    description: "What your tool does",
    inputSchema: {
        type: "object",
        properties: {
            param1: { type: "string", description: "Parameter description" }
        },
        required: ["param1"],
        additionalProperties: false
    },
    // Optional but recommended: lets clients validate structuredContent.
    outputSchema: {
        type: "object",
        properties: { result: { type: "string" } },
        required: ["result"]
    }
};

async function execute(args = {}, context = {}) {
    const { param1 } = args;

    // context.reportProgress({ progress, total, message }) streams progress
    // when the client sent a progressToken.
    // context.signal aborts when the client closes the stream.
    // context.clientInfo / context.clientCapabilities describe the caller.

    const structuredContent = { result: `Processed: ${param1}` };

    return {
        content: [{ type: "text", text: JSON.stringify(structuredContent) }],
        structuredContent
    };
}

module.exports = { definition: TOOL_DEFINITION, execute };

Arguments are validated against inputSchema before execute runs. Throwing from execute produces a tool execution error (isError: true) rather than a JSON-RPC error, so the model can self-correct.

2. Auto-Loading

Save the file in /tools and restart the server (or set MCP_WATCH_TOOLS=true to hot-reload and notify subscribers).

3. Stateful tools

MCP has no protocol-level session. If a tool needs state across calls, return an opaque handle and accept it as an argument on later calls β€” document its lifetime in the tool description so the model knows when to create a new one.

4. Asking the client for input (MRTR)

Instead of sending a server-initiated elicitation/create request, return an input-required result and let the client retry:

return {
    resultType: "input_required",
    inputRequests: {
        github_login: {
            method: "elicitation/create",
            params: {
                mode: "form",
                message: "Please provide your GitHub username",
                requestedSchema: {
                    type: "object",
                    properties: { name: { type: "string" } },
                    required: ["name"]
                }
            }
        }
    },
    // Anything you need to resume; it comes back on the retry.
    requestState: "..."
};

The retry arrives as a new tools/call with context.inputResponses and context.requestState populated.

5. Exposing a parameter as an HTTP header

Annotate a primitive, statically reachable property with x-mcp-header so intermediaries can route on it without parsing the body:

region: { type: "string", description: "...", "x-mcp-header": "Region" }

Conforming clients then send Mcp-Param-Region: us-west1, and the server rejects any request where the header and the argument disagree. Never annotate secrets β€” header values are visible to every intermediary on the path.

πŸ”— MCP Client Integration

{
  "mcpServers": {
    "template": {
      "type": "http",
      "url": "http://127.0.0.1:3202/mcp",
      "headers": {
        "Authorization": "Bearer your-api-key"
      }
    }
  }
}

πŸ“ Layout

mcp-server.js        Express app, routing, request validation, dispatch
lib/protocol.js      Version constants, _meta keys, error codes, message builders
lib/headers.js       Request-metadata headers, base64 sentinel, x-mcp-header
lib/schema.js        Tool argument validation
lib/sse.js           SSE response streams (no resumability, per spec)
lib/subscriptions.js subscriptions/listen stream management
lib/security.js      Origin validation, API key auth, RFC 9728 metadata
tools/               Auto-loaded tools
test/                Protocol conformance tests

Endpoints

Endpoint Purpose
POST /mcp The MCP endpoint β€” the only method it accepts
GET /mcp, DELETE /mcp 405: the standalone SSE stream and session termination are gone
GET /health Status, protocol version, open subscriptions
GET /tools/config Tool definitions for wiring into an agent config
GET /.well-known/oauth-protected-resource RFC 9728 metadata, when configured

License

This server is provided as-is for demonstration purposes. Please review and enhance security measures before production use.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages