Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

feat(mcp): add the JSON-RPC envelope for a dual-era MCP endpoint

spacesdrive2a5e6fa7f893
diff --git a/backend/lib/mcp/protocol.ts b/backend/lib/mcp/protocol.ts
new file mode 100644
index 0000000..357b84f
--- /dev/null
+++ b/backend/lib/mcp/protocol.ts
@@ -0,0 +1,186 @@
+// the Model Context Protocol's JSON-RPC envelope over Streamable HTTP, for a stateless, tools-only server that serves
+// the handshake-based revisions Claude's hosted apps speak and the per-request revision 2026-07-28 on one endpoint
+
+export const MODERN_VERSION = '2026-07-28';
+// newest first; initialize answers with the client's version when it is one of these, otherwise the newest
+export const LEGACY_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26'] as const;
+export const SUPPORTED_VERSIONS: readonly string[] = [MODERN_VERSION, ...LEGACY_VERSIONS];
+// the transport spec says a request with no version header comes from a 2025-03-26 client
+const UNNAMED_LEGACY_VERSION = '2025-03-26';
+
+const META_VERSION = 'io.modelcontextprotocol/protocolVersion';
+const META_SERVER_INFO = 'io.modelcontextprotocol/serverInfo';
+
+// JSON-RPC's own codes, then the two the MCP transport adds
+export const RPC_ERROR = {
+ parse: -32700,
+ invalidRequest: -32600,
+ methodNotFound: -32601,
+ invalidParams: -32602,
+ internal: -32603,
+ headerMismatch: -32020,
+ unsupportedVersion: -32022,
+} as const;
+
+export type JsonRpcId = string | number;
+export type JsonObject = Record<string, unknown>;
+
+// a request has an id and expects a reply; a notification has none and gets 202
+export interface RpcMessage {
+ id: JsonRpcId | null;
+ method: string;
+ params: JsonObject;
+}
+
+export interface RpcError {
+ code: number;
+ message: string;
+ data?: unknown;
+}
+
+export type RpcResponse =
+ | { jsonrpc: '2.0'; id: JsonRpcId | null; result: unknown }
+ | { jsonrpc: '2.0'; id: JsonRpcId | null; error: RpcError };
+
+// what the endpoint sends back: the HTTP status and a JSON body, or none for an accepted notification
+export interface McpReply {
+ status: number;
+ body: RpcResponse | null;
+}
+
+// legacy requests follow the initialize handshake's rules; modern ones carry their version in _meta and in headers
+export type Era = { kind: 'legacy'; version: string } | { kind: 'modern'; version: string };
+
+// the request headers the transport reads, already looked up by name; undefined when absent
+export interface McpHeaders {
+ protocolVersion?: string;
+ method?: string;
+ name?: string;
+}
+
+export interface ServerIdentity {
+ name: string;
+ title: string;
+ version: string;
+ instructions: string;
+}
+
+function isObject(value: unknown): value is JsonObject {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+export function resultReply(id: JsonRpcId | null, result: unknown, status = 200): McpReply {
+ return { status, body: { jsonrpc: '2.0', id, result } };
+}
+
+export function errorReply(id: JsonRpcId | null, code: number, message: string, status: number, data?: unknown): McpReply {
+ return { status, body: { jsonrpc: '2.0', id, error: data === undefined ? { code, message } : { code, message, data } } };
+}
+
+// one message per POST; batches were removed from the protocol in 2025-06-18, and clients never send responses
+export function parseMessage(body: unknown): RpcMessage | McpReply {
+ if (!isObject(body) || body.jsonrpc !== '2.0') {
+ return errorReply(null, RPC_ERROR.invalidRequest, 'Send one JSON-RPC 2.0 request or notification per POST.', 400);
+ }
+ const { id, method, params } = body;
+ const validId = id === undefined || typeof id === 'string' || (typeof id === 'number' && Number.isFinite(id));
+ if (typeof method !== 'string' || method === '' || !validId) {
+ return errorReply(null, RPC_ERROR.invalidRequest, 'A JSON-RPC request needs a method name and a string or number id.', 400);
+ }
+ if (params !== undefined && !isObject(params)) {
+ return errorReply(id ?? null, RPC_ERROR.invalidParams, 'params must be an object.', 400);
+ }
+ return { id: id ?? null, method, params: params ?? {} };
+}
+
+export function isReply(value: RpcMessage | McpReply): value is McpReply {
+ return 'status' in value;
+}
+
+// a value the client could not send as a plain header arrives as =?base64?<value>?=
+export function decodeHeaderValue(value: string): string | null {
+ const encoded = /^=\?base64\?([A-Za-z0-9+/]*={0,2})\?=$/i.exec(value);
+ if (!encoded) return value;
+ try {
+ return new TextDecoder('utf-8', { fatal: true, ignoreBOM: false }).decode(Uint8Array.from(atob(encoded[1]), char => char.charCodeAt(0)));
+ } catch {
+ // not base64 or not UTF-8, so it cannot match anything in the body
+ return null;
+ }
+}
+
+// a request carrying the version in _meta is modern; anything else follows the version its header names
+export function requestEra(message: RpcMessage, headers: McpHeaders): Era {
+ const meta = isObject(message.params._meta) ? message.params._meta : {};
+ const metaVersion = meta[META_VERSION];
+ if (typeof metaVersion === 'string') return { kind: 'modern', version: metaVersion };
+ return { kind: 'legacy', version: headers.protocolVersion ?? UNNAMED_LEGACY_VERSION };
+}
+
+// what makes a request unusable before its method runs: an unknown version, or headers that disagree with the body
+export function checkEnvelope(message: RpcMessage, era: Era, headers: McpHeaders): McpReply | null {
+ if (era.kind === 'legacy') {
+ // initialize names its version in the body and is answered with one we support, so only later requests are checked
+ if (message.method === 'initialize' || (LEGACY_VERSIONS as readonly string[]).includes(era.version)) return null;
+ return unsupportedVersion(message.id, era.version);
+ }
+ if (era.version !== MODERN_VERSION) return unsupportedVersion(message.id, era.version);
+ if (headers.protocolVersion !== era.version) return headerMismatch(message.id, 'MCP-Protocol-Version', headers.protocolVersion, era.version);
+ if (message.id !== null && headers.method !== message.method) return headerMismatch(message.id, 'Mcp-Method', headers.method, message.method);
+ if (message.method === 'tools/call') {
+ const name = typeof message.params.name === 'string' ? message.params.name : undefined;
+ const sent = headers.name === undefined ? undefined : decodeHeaderValue(headers.name) ?? undefined;
+ if (sent !== name) return headerMismatch(message.id, 'Mcp-Name', headers.name, name);
+ }
+ return null;
+}
+
+function unsupportedVersion(id: JsonRpcId | null, requested: string): McpReply {
+ return errorReply(id, RPC_ERROR.unsupportedVersion, 'Unsupported protocol version', 400, { supported: SUPPORTED_VERSIONS, requested });
+}
+
+function headerMismatch(id: JsonRpcId | null, header: string, sent: string | undefined, expected: string | undefined): McpReply {
+ const message = sent === undefined
+ ? `Header mismatch: the ${header} header is missing`
+ : `Header mismatch: ${header} header value '${sent}' does not match body value '${expected ?? ''}'`;
+ return errorReply(id, RPC_ERROR.headerMismatch, message, 400);
+}
+
+// modern servers answer an unknown method with 404 so intermediaries can tell it apart from a bad request
+export function methodNotFound(message: RpcMessage, era: Era): McpReply {
+ return errorReply(message.id, RPC_ERROR.methodNotFound, `Unknown method: ${message.method}`, era.kind === 'modern' ? 404 : 200);
+}
+
+export function negotiateLegacyVersion(requested: unknown): string {
+ return typeof requested === 'string' && (LEGACY_VERSIONS as readonly string[]).includes(requested) ? requested : LEGACY_VERSIONS[0];
+}
+
+export function initializeResult(params: JsonObject, server: ServerIdentity): JsonObject {
+ return {
+ protocolVersion: negotiateLegacyVersion(params.protocolVersion),
+ capabilities: { tools: { listChanged: false } },
+ serverInfo: { name: server.name, title: server.title, version: server.version },
+ instructions: server.instructions,
+ };
+}
+
+// cached privately per client for an hour: the tool list depends on what the caller is allowed to do
+const DISCOVERY_TTL_MS = 60 * 60 * 1000;
+
+export function discoverResult(server: ServerIdentity): JsonObject {
+ return {
+ resultType: 'complete',
+ supportedVersions: SUPPORTED_VERSIONS,
+ capabilities: { tools: {} },
+ _meta: { [META_SERVER_INFO]: { name: server.name, title: server.title, version: server.version } },
+ instructions: server.instructions,
+ ttlMs: DISCOVERY_TTL_MS,
+ cacheScope: 'private',
+ };
+}
+
+// modern results say they are complete, and list results say how long and for whom they may be cached
+export function eraResult(era: Era, result: JsonObject, cacheable = false): JsonObject {
+ if (era.kind === 'legacy') return result;
+ return cacheable ? { resultType: 'complete', ...result, ttlMs: DISCOVERY_TTL_MS, cacheScope: 'private' } : { resultType: 'complete', ...result };
+}
diff --git a/backend/tests/lib/mcp/protocol.test.ts b/backend/tests/lib/mcp/protocol.test.ts
new file mode 100644
index 0000000..3846b9f
--- /dev/null
+++ b/backend/tests/lib/mcp/protocol.test.ts
@@ -0,0 +1,107 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import {
+ MODERN_VERSION, RPC_ERROR, checkEnvelope, decodeHeaderValue, discoverResult, eraResult, initializeResult, isReply,
+ methodNotFound, parseMessage, requestEra,
+} from '../../../lib/mcp/protocol.ts';
+import type { McpHeaders, McpReply, RpcMessage } from '../../../lib/mcp/protocol.ts';
+
+const SERVER = { name: 'twiligent', title: 'Twiligent', version: '2.0.0', instructions: 'Use the tools.' };
+const MODERN_META = { _meta: { 'io.modelcontextprotocol/protocolVersion': MODERN_VERSION } };
+
+function message(body: unknown): RpcMessage {
+ const parsed = parseMessage(body);
+ if (isReply(parsed)) throw new Error('expected a message');
+ return parsed;
+}
+
+function errorCode(reply: McpReply | null): number | undefined {
+ return reply?.body && 'error' in reply.body ? reply.body.error.code : undefined;
+}
+
+test('a request keeps its id, method and params, and a notification has a null id', () => {
+ assert.deepEqual(message({ jsonrpc: '2.0', id: 7, method: 'tools/list' }), { id: 7, method: 'tools/list', params: {} });
+ assert.equal(message({ jsonrpc: '2.0', method: 'notifications/initialized' }).id, null);
+});
+
+test('a batch, a response or a body without a method is refused as an invalid request', () => {
+ for (const body of [[{ jsonrpc: '2.0', id: 1, method: 'ping' }], { jsonrpc: '2.0', id: 1, result: {} }, { id: 1, method: 'ping' }, 'ping']) {
+ const parsed = parseMessage(body);
+ assert.ok(isReply(parsed));
+ assert.equal(parsed.status, 400);
+ assert.equal(errorCode(parsed), RPC_ERROR.invalidRequest);
+ }
+});
+
+test('params that are not an object are invalid params', () => {
+ const parsed = parseMessage({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: ['x'] });
+ assert.ok(isReply(parsed));
+ assert.equal(errorCode(parsed), RPC_ERROR.invalidParams);
+});
+
+test('a request with the version in _meta is modern; one without follows its header or 2025-03-26', () => {
+ const modern = message({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: MODERN_META });
+ assert.deepEqual(requestEra(modern, {}), { kind: 'modern', version: MODERN_VERSION });
+ const legacy = message({ jsonrpc: '2.0', id: 1, method: 'tools/list' });
+ assert.deepEqual(requestEra(legacy, { protocolVersion: '2025-11-25' }), { kind: 'legacy', version: '2025-11-25' });
+ assert.deepEqual(requestEra(legacy, {}), { kind: 'legacy', version: '2025-03-26' });
+});
+
+test('a modern request needs headers that match its body', () => {
+ const call = message({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'list_accounts', ...MODERN_META } });
+ const era = requestEra(call, {});
+ const good: McpHeaders = { protocolVersion: MODERN_VERSION, method: 'tools/call', name: 'list_accounts' };
+ assert.equal(checkEnvelope(call, era, good), null);
+ for (const headers of [{ ...good, protocolVersion: undefined }, { ...good, method: 'tools/list' }, { ...good, name: 'delete_media' }, { ...good, name: undefined }]) {
+ const reply = checkEnvelope(call, era, headers);
+ assert.equal(reply?.status, 400);
+ assert.equal(errorCode(reply), RPC_ERROR.headerMismatch);
+ }
+});
+
+test('a tool name sent base64 encoded in Mcp-Name is decoded before it is compared', () => {
+ assert.equal(decodeHeaderValue(`=?base64?${btoa('list_accounts')}?=`), 'list_accounts');
+ assert.equal(decodeHeaderValue('list_accounts'), 'list_accounts');
+ assert.equal(decodeHeaderValue('=?base64?***?='), '=?base64?***?=');
+ const call = message({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'list_accounts', ...MODERN_META } });
+ const headers = { protocolVersion: MODERN_VERSION, method: 'tools/call', name: `=?base64?${btoa('list_accounts')}?=` };
+ assert.equal(checkEnvelope(call, requestEra(call, {}), headers), null);
+});
+
+test('an unknown version is refused with the versions the server supports', () => {
+ const modern = message({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: { _meta: { 'io.modelcontextprotocol/protocolVersion': '1900-01-01' } } });
+ const reply = checkEnvelope(modern, requestEra(modern, {}), { protocolVersion: '1900-01-01', method: 'tools/list' });
+ assert.equal(reply?.status, 400);
+ assert.equal(errorCode(reply), RPC_ERROR.unsupportedVersion);
+ const legacy = message({ jsonrpc: '2.0', id: 2, method: 'tools/list' });
+ assert.equal(errorCode(checkEnvelope(legacy, requestEra(legacy, { protocolVersion: '2024-01-01' }), { protocolVersion: '2024-01-01' })), RPC_ERROR.unsupportedVersion);
+});
+
+test('initialize answers with the client version when supported, otherwise the newest legacy version, and no session', () => {
+ assert.equal(initializeResult({ protocolVersion: '2025-06-18' }, SERVER).protocolVersion, '2025-06-18');
+ assert.equal(initializeResult({ protocolVersion: '2099-01-01' }, SERVER).protocolVersion, '2025-11-25');
+ assert.deepEqual(initializeResult({}, SERVER).capabilities, { tools: { listChanged: false } });
+ const init = message({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2099-01-01' } });
+ assert.equal(checkEnvelope(init, requestEra(init, {}), {}), null);
+});
+
+test('discovery lists every supported version and is cached privately', () => {
+ const result = discoverResult(SERVER);
+ assert.deepEqual(result.supportedVersions, ['2026-07-28', '2025-11-25', '2025-06-18', '2025-03-26']);
+ assert.equal(result.cacheScope, 'private');
+ assert.equal(result.resultType, 'complete');
+});
+
+test('modern results are marked complete and legacy results are left as they are', () => {
+ assert.deepEqual(eraResult({ kind: 'legacy', version: '2025-11-25' }, { tools: [] }), { tools: [] });
+ assert.deepEqual(eraResult({ kind: 'modern', version: MODERN_VERSION }, { content: [] }), { resultType: 'complete', content: [] });
+ assert.equal(eraResult({ kind: 'modern', version: MODERN_VERSION }, { tools: [] }, true).cacheScope, 'private');
+});
+
+test('an unknown method is a 404 for modern clients and a JSON-RPC error with 200 for legacy ones', () => {
+ const unknown = message({ jsonrpc: '2.0', id: 3, method: 'resources/list' });
+ assert.equal(methodNotFound(unknown, { kind: 'modern', version: MODERN_VERSION }).status, 404);
+ const legacy = methodNotFound(unknown, { kind: 'legacy', version: '2025-11-25' });
+ assert.equal(legacy.status, 200);
+ assert.equal(errorCode(legacy), RPC_ERROR.methodNotFound);
+});