Context7 Platform -- Up-to-date docs for AI agents
feat: add sessions to MCP server (#2655)
Enes Gulesaf6a7b5af101
diff --git a/.changeset/strict-feet-end.md b/.changeset/strict-feet-end.mdnew file mode 100644index 00000000..6a3c7ab7--- /dev/null+++ b/.changeset/strict-feet-end.md@@ -0,0 +1,5 @@+---+"@upstash/context7-mcp": major+---++Convert the stateless MCP implementation to a stateful one using Redis for session management.diff --git a/.env.example b/.env.examplenew file mode 100644index 00000000..3c7ccc04--- /dev/null+++ b/.env.example@@ -0,0 +1,24 @@+# Context7 API+CONTEXT7_API_KEY=+CONTEXT7_API_URL=https://context7.com/api++# MCP HTTP server+UPSTASH_REDIS_REST_URL=+UPSTASH_REDIS_REST_TOKEN=+RESOURCE_URL=+AUTH_SERVER_URL=+OPENAI_APPS_CHALLENGE_TOKEN=+CLIENT_IP_ENCRYPTION_KEY=++# Network / certificates+HTTPS_PROXY=+NODE_EXTRA_CA_CERTS=++# GitHub integration+GITHUB_TOKEN=+GH_TOKEN=++# CLI behavior+CLAUDE_CONFIG_DIR=+CTX7_TELEMETRY_DISABLED=+EDITOR=diff --git a/packages/mcp/package.json b/packages/mcp/package.jsonindex 248e0a9f..40eb8f0c 100644--- a/packages/mcp/package.json+++ b/packages/mcp/package.json@@ -47,6 +47,7 @@"dependencies": {"@modelcontextprotocol/sdk": "^1.25.1","@types/express": "^5.0.4",+ "@upstash/redis": "^1.38.0","commander": "^14.0.0","express": "^5.1.0","jose": "^6.1.3",diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.tsindex 77392b36..cd541eb7 100644--- a/packages/mcp/src/index.ts+++ b/packages/mcp/src/index.ts@@ -10,8 +10,11 @@ import { formatSearchResults, extractClientInfoFromUserAgent } from "./lib/utilsimport { isJWT, validateJWT } from "./lib/jwt.js";import express from "express";import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";+import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";import { Command } from "commander";import { AsyncLocalStorage } from "async_hooks";+import { randomUUID } from "node:crypto";+import { createSessionStore } from "./lib/sessionStore.js";import {SERVER_VERSION,RESOURCE_URL,@@ -77,6 +80,8 @@ const requestContext = new AsyncLocalStorage<ClientContext>();// Global state for stdio mode onlylet stdioApiKey: string | undefined;let stdioClientInfo: { ide?: string; version?: string } | undefined;+// One session ID per stdio process.+let stdioSessionId: string | undefined;/*** Get the effective client context@@ -94,6 +99,7 @@ function getClientContext(): ClientContext {apiKey: stdioApiKey,clientInfo: stdioClientInfo,transport: "stdio",+ sessionId: stdioSessionId,};}@@ -384,14 +390,16 @@ async function main() {);};+ const sessionStore = createSessionStore();+const handleMcpRequest = async (req: express.Request,res: express.Response,requireAuth: boolean) => {- // Reject GET requests — this server is stateless and does not send server-initiated- // notifications, so SSE streams serve no purpose and cause mass NGINX timeouts.- // Returning 405 is spec-compliant per MCP StreamableHTTP (2025-03-26).+ // Reject GET requests — sessions are tracked in Redis, but this server does not send+ // server-initiated notifications, so SSE streams serve no purpose and cause mass NGINX+ // timeouts. Returning 405 is spec-compliant per MCP StreamableHTTP (2025-03-26).if (req.method === "GET") {return res.status(405).json({jsonrpc: "2.0",@@ -445,6 +453,53 @@ async function main() {transport: "http",};+ const sessionId = extractHeaderValue(req.headers["mcp-session-id"]);++ if (req.method === "DELETE") {+ if (!sessionId) {+ return res.status(400).json({+ jsonrpc: "2.0",+ error: { code: -32000, message: "Bad Request: No valid session ID provided" },+ id: null,+ });+ }+ await sessionStore.delete(sessionId);+ return res.status(200).end();+ }++ let effectiveSessionId: string;+ if (!sessionId && req.method === "POST" && isInitializeRequest(req.body)) {+ effectiveSessionId = randomUUID();+ await sessionStore.create(effectiveSessionId);+ res.setHeader("mcp-session-id", effectiveSessionId);+ } else if (sessionId && req.method === "POST" && !isInitializeRequest(req.body)) {+ const sessionExists = await sessionStore.refresh(sessionId);+ if (!sessionExists) {+ // Per MCP Streamable HTTP spec: 404 signals to the client that the session+ // has been terminated/expired, so it should re-initialize with a fresh InitializeRequest.+ return res.status(404).json({+ jsonrpc: "2.0",+ error: {+ code: -32000,+ message: "Session not found or expired. Please re-initialize.",+ },+ id: null,+ });+ }+ effectiveSessionId = sessionId;+ } else {+ return res.status(400).json({+ jsonrpc: "2.0",+ error: { code: -32000, message: "Bad Request: No valid session ID provided" },+ id: null,+ });+ }++ context.sessionId = effectiveSessionId;++ // sessionIdGenerator is undefined because session lifecycle (create/refresh/delete)+ // is owned by the route handler above and persisted in Redis, not by the SDK transport.+ //// Use SSE responses for tool calls (enableJsonResponse: false). The SDK then// flushes response headers immediately after parsing the request rather than// buffering until the tool returns. This is required for long-running tools@@ -461,9 +516,10 @@ async function main() {server.close();});+ installTransportArgAliasing(transport);+ await server.connect(transport);+await requestContext.run(context, async () => {- installTransportArgAliasing(transport);- await server.connect(transport);await transport.handleRequest(req, res, req.body);});} catch (error) {@@ -577,6 +633,7 @@ async function main() {startServer(initialPort);} else {stdioApiKey = cliOptions.apiKey || process.env.CONTEXT7_API_KEY;+ stdioSessionId = randomUUID();process.stdin.on("end", () => process.exit(0));process.stdin.on("close", () => process.exit(0));diff --git a/packages/mcp/src/lib/encryption.ts b/packages/mcp/src/lib/encryption.tsindex f0b5d22e..91ceb1f4 100644--- a/packages/mcp/src/lib/encryption.ts+++ b/packages/mcp/src/lib/encryption.ts@@ -42,6 +42,9 @@ export function generateHeaders(context: ClientContext): Record<string, string>if (context.clientIp) {headers["mcp-client-ip"] = encryptClientIp(context.clientIp);}+ if (context.sessionId) {+ headers["mcp-session-id"] = context.sessionId;+ }if (context.apiKey) {headers["Authorization"] = `Bearer ${context.apiKey}`;}diff --git a/packages/mcp/src/lib/redis.ts b/packages/mcp/src/lib/redis.tsnew file mode 100644index 00000000..c71bb0cb--- /dev/null+++ b/packages/mcp/src/lib/redis.ts@@ -0,0 +1,17 @@+import { Redis } from "@upstash/redis";++let cached: Redis | undefined;++/**+ * Returns the shared Upstash Redis client. Throws if credentials are missing.+ */+export function getRedis(): Redis {+ if (cached) return cached;+ if (!process.env.UPSTASH_REDIS_REST_URL || !process.env.UPSTASH_REDIS_REST_TOKEN) {+ throw new Error(+ "Upstash Redis credentials are required. Set UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN."+ );+ }+ cached = Redis.fromEnv();+ return cached;+}diff --git a/packages/mcp/src/lib/sessionStore.ts b/packages/mcp/src/lib/sessionStore.tsnew file mode 100644index 00000000..da5d26b3--- /dev/null+++ b/packages/mcp/src/lib/sessionStore.ts@@ -0,0 +1,41 @@+import { getRedis } from "./redis.js";++const SESSION_TTL_SECONDS = 7 * 24 * 60 * 60; // 7 days+const SESSION_KEY_PREFIX = "#mcp#session#";++// Fail-open: log Redis errors and proceed. The session ID isn't an auth/authz+// primitive — only an opaque identifier for log correlation and spec compliance —+// so an unreachable Redis shouldn't block clients. Ghost sessions self-heal on+// the next refresh (returns false → client gets 404 → re-inits).+export function createSessionStore() {+ const redis = getRedis();++ const getSessionKey = (sessionId: string) => `${SESSION_KEY_PREFIX}${sessionId}`;++ return {+ async create(sessionId: string) {+ try {+ await redis.set(getSessionKey(sessionId), "1", { ex: SESSION_TTL_SECONDS });+ } catch (err) {+ console.error(`Error creating Redis session record ${sessionId}:`, err);+ }+ },++ async refresh(sessionId: string) {+ try {+ return (await redis.expire(getSessionKey(sessionId), SESSION_TTL_SECONDS)) === 1;+ } catch (err) {+ console.error(`Error refreshing Redis session record ${sessionId}:`, err);+ return true;+ }+ },++ async delete(sessionId: string) {+ try {+ await redis.del(getSessionKey(sessionId));+ } catch (err) {+ console.error(`Error deleting Redis session record ${sessionId}:`, err);+ }+ },+ };+}diff --git a/packages/mcp/src/lib/types.ts b/packages/mcp/src/lib/types.tsindex 483dd6b7..3b5a024f 100644--- a/packages/mcp/src/lib/types.ts+++ b/packages/mcp/src/lib/types.ts@@ -40,6 +40,7 @@ export interface ClientContext {version?: string;};transport?: "stdio" | "http";+ sessionId?: string;/** Mutable: set by the upstream API layer when the backend signals the* client should be prompted to sign in. Read by the auth-prompt wrapper. */shouldPrompt?: boolean;diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 1b34ebfd..1697e217 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -112,6 +112,9 @@ importers:'@types/express':specifier: ^5.0.4version: 5.0.5+ '@upstash/redis':+ specifier: ^1.38.0+ version: 1.38.0commander:specifier: ^14.0.0version: 14.0.2@@ -1115,6 +1118,9 @@ packages:resolution: {integrity: sha512-SIV3/6eftCy1bNzCQoPmbWsRLujS8t5iDIZ4spZOBHqrM+yfX2ogg8Tt3PDTAVKw3sSCiUgg30uOAvK2r9zGjQ==}engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}+ '@upstash/[email protected]':+ resolution: {integrity: sha512-wu+dZBptlLy0+MCUEoHmzrY/TnmgDey3+c7EbIGwrLqAvkP8yi5MWZHYGIFtAygmL4Bkz2TdFu+eU0vFPncIcg==}+'@vercel/[email protected]':resolution: {integrity: sha512-Fw28YZpRnA3cAHHDlkt7xQHiJ0fcL+NRcIqsocZQUSmbzeIKRpwttJjik5ZGanXP+vlA4SbTg+AbA3bP363l+w==}engines: {node: '>= 20'}@@ -2384,6 +2390,9 @@ packages:resolution: {integrity: sha512-9a4/uxlTWJ4+a5i0ooc1rU7C7YOw3wT+UGqdeNNHWnOF9qcMBgLRS+4IYUqbczewFx4mLEig6gawh7X6mFlEkA==}+ resolution: {integrity: sha512-Ql87qFHB3s/De2ClA9e0gsnS6zXG27SkTiSJwjCc9MebbfapQfuPzumMIUMi38ezPZVNFcHI9sUIepeQfw8J8Q==}+resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}@@ -3422,6 +3431,10 @@ snapshots:'@typescript-eslint/types': 8.47.0eslint-visitor-keys: 4.2.1+ '@upstash/[email protected]':+ dependencies:+ uncrypto: 0.1.3+'@vercel/[email protected]': {}'@vitest/[email protected]':@@ -4699,6 +4712,8 @@ snapshots:+ [email protected]: {}+