MCP Server Template

MCP Server Template

A template MCP server implementing the 2026-07-28 spec with dynamic tool loading, API key authentication, and sample calculator and timestamp tools.

Category
访问服务器

README

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.

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选