Context7 Platform -- Up-to-date docs for AI agents
CTX7-971: Client Metrics (#1305)
Fahreddin Özcan368b143356e9
diff --git a/.changeset/wise-loops-like.md b/.changeset/wise-loops-like.mdnew file mode 100644index 00000000..bc1c84b1--- /dev/null+++ b/.changeset/wise-loops-like.md@@ -0,0 +1,5 @@+---+"@upstash/context7-mcp": patch+---++Collect client and server version metricsdiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex ae3ded06..52649590 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -61,17 +61,6 @@ jobs:echo "mcp_version=$VERSION" >> $GITHUB_OUTPUTfi- - name: Update version in MCP source file- if: steps.check-mcp.outputs.mcp_published == 'true'- run: |- VERSION="${{ steps.check-mcp.outputs.mcp_version }}"- sed -i "s/version: \"[0-9]*\.[0-9]*\.[0-9]*\"/version: \"$VERSION\"/" packages/mcp/src/index.ts- git config user.name "github-actions[bot]"- git config user.email "github-actions[bot]@users.noreply.github.com"- git add packages/mcp/src/index.ts- git commit -m "chore: update MCP version in source to $VERSION" || true- git push || true-- name: Update server.jsonif: steps.check-mcp.outputs.mcp_published == 'true'run: |diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.tsindex ad83be08..671bd33c 100644--- a/packages/mcp/src/index.ts+++ b/packages/mcp/src/index.ts@@ -4,11 +4,13 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";import { z } from "zod";import { searchLibraries, fetchLibraryContext } from "./lib/api.js";-import { formatSearchResults } from "./lib/utils.js";+import { ClientContext } from "./lib/encryption.js";+import { formatSearchResults, extractClientInfoFromUserAgent } from "./lib/utils.js";import express from "express";import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";import { Command } from "commander";import { AsyncLocalStorage } from "async_hooks";+import { SERVER_VERSION } from "./lib/constants.js";/** Default HTTP server port */const DEFAULT_PORT = 3000;@@ -61,14 +63,35 @@ const CLI_PORT = (() => {return isNaN(parsed) ? undefined : parsed;})();-const requestContext = new AsyncLocalStorage<{- clientIp?: string;- apiKey?: string;-}>();+const requestContext = new AsyncLocalStorage<ClientContext>();++// Global state for stdio mode only+let stdioApiKey: string | undefined;+let stdioClientInfo: { ide?: string; version?: string } | undefined;++/**+ * Get the effective client context+ */+function getClientContext(): ClientContext {+ const ctx = requestContext.getStore();++ // HTTP mode: context is fully populated from request+ if (ctx) {+ return ctx;+ }-// Store API key globally for stdio mode (where requestContext may not be available in tool handlers)-let globalApiKey: string | undefined;+ // stdio mode: use globals+ return {+ apiKey: stdioApiKey,+ clientInfo: stdioClientInfo,+ transport: "stdio",+ };+}+/**+ * Extract client IP address from request headers.+ * Handles X-Forwarded-For header for proxied requests.+ */function getClientIp(req: express.Request): string | undefined {const forwardedFor = req.headers["x-forwarded-for"] || req.headers["X-Forwarded-For"];@@ -98,7 +121,7 @@ function getClientIp(req: express.Request): string | undefined {const server = new McpServer({name: "Context7",- version: "2.0.0",+ version: SERVER_VERSION,},{instructions:@@ -106,6 +129,17 @@ const server = new McpServer(});+// Capture client info from MCP initialize handshake+server.server.oninitialized = () => {+ const clientVersion = server.server.getClientVersion();+ if (clientVersion) {+ stdioClientInfo = {+ ide: clientVersion.name,+ version: clientVersion.version,+ };+ }+};+server.registerTool("resolve-library-id",{@@ -147,9 +181,7 @@ IMPORTANT: Do not call this tool more than 3 times per question. If you cannot f},},async ({ query, libraryName }) => {- const ctx = requestContext.getStore();- const apiKey = ctx?.apiKey || globalApiKey;- const searchResponse = await searchLibraries(query, libraryName, ctx?.clientIp, apiKey);+ const searchResponse = await searchLibraries(query, libraryName, getClientContext());if (!searchResponse.results || searchResponse.results.length === 0) {return {@@ -220,10 +252,7 @@ IMPORTANT: Do not call this tool more than 3 times per question. If you cannot f},},async ({ query, libraryId }) => {- const ctx = requestContext.getStore();- const apiKey = ctx?.apiKey || globalApiKey;-- const response = await fetchLibraryContext({ query, libraryId }, ctx?.clientIp, apiKey);+ const response = await fetchLibraryContext({ query, libraryId }, getClientContext());return {content: [@@ -289,8 +318,12 @@ async function main() {app.all("/mcp", async (req: express.Request, res: express.Response) => {try {- const clientIp = getClientIp(req);- const apiKey = extractApiKey(req);+ const context: ClientContext = {+ clientIp: getClientIp(req),+ apiKey: extractApiKey(req),+ clientInfo: extractClientInfoFromUserAgent(req.headers["user-agent"]),+ transport: "http",+ };const transport = new StreamableHTTPServerTransport({sessionIdGenerator: undefined,@@ -301,7 +334,7 @@ async function main() {transport.close();});- await requestContext.run({ clientIp, apiKey }, async () => {+ await requestContext.run(context, async () => {await server.connect(transport);await transport.handleRequest(req, res, req.body);});@@ -344,22 +377,19 @@ async function main() {httpServer.once("listening", () => {console.error(- `Context7 Documentation MCP Server running on HTTP at http://localhost:${port}/mcp`+ `Context7 Documentation MCP Server v${SERVER_VERSION} running on HTTP at http://localhost:${port}/mcp`);});};startServer(initialPort);} else {- const apiKey = cliOptions.apiKey || process.env.CONTEXT7_API_KEY;- globalApiKey = apiKey; // Store globally for tool handlers in stdio mode+ stdioApiKey = cliOptions.apiKey || process.env.CONTEXT7_API_KEY;const transport = new StdioServerTransport();- await requestContext.run({ apiKey }, async () => {- await server.connect(transport);- });+ await server.connect(transport);- console.error("Context7 Documentation MCP Server running on stdio");+ console.error(`Context7 Documentation MCP Server v${SERVER_VERSION} running on stdio`);}}diff --git a/packages/mcp/src/lib/api.ts b/packages/mcp/src/lib/api.tsindex 830b1497..4624f03d 100644--- a/packages/mcp/src/lib/api.ts+++ b/packages/mcp/src/lib/api.ts@@ -1,5 +1,5 @@import { SearchResponse, ContextRequest, ContextResponse } from "./types.js";-import { generateHeaders } from "./encryption.js";+import { ClientContext, generateHeaders } from "./encryption.js";import { ProxyAgent, setGlobalDispatcher } from "undici";const CONTEXT7_API_BASE_URL = "https://context7.com/api";@@ -21,7 +21,6 @@ async function parseErrorResponse(response: Response, apiKey?: string): Promise<// JSON parsing failed, fall through to default}- // Fallback for non-JSON responsesconst status = response.status;if (status === 429) {return apiKey@@ -37,7 +36,6 @@ async function parseErrorResponse(response: Response, apiKey?: string): Promise<return `Request failed with status ${status}. Please try again later.`;}-// Pick up proxy configuration in a variety of common env var names.const PROXY_URL: string | null =process.env.HTTPS_PROXY ??process.env.https_proxy ??@@ -47,13 +45,8 @@ const PROXY_URL: string | null =if (PROXY_URL && !PROXY_URL.startsWith("$") && /^(http|https):\/\//i.test(PROXY_URL)) {try {- // Configure a global proxy agent once at startup. Subsequent fetch calls will- // automatically use this dispatcher.- // Using `any` cast because ProxyAgent implements the Dispatcher interface but- // TS may not infer it correctly in some versions.setGlobalDispatcher(new ProxyAgent(PROXY_URL));} catch (error) {- // Don't crash the app if proxy initialisation fails – just log a warning.console.error(`[Context7] Failed to configure proxy agent for provided proxy URL: ${PROXY_URL}:`,error@@ -65,63 +58,56 @@ if (PROXY_URL && !PROXY_URL.startsWith("$") && /^(http|https):\/\//i.test(PROXY_* Searches for libraries matching the given query* @param query The user's question or task (used for LLM relevance ranking)* @param libraryName The library name to search for in the database- * @param clientIp Optional client IP address to include in headers- * @param apiKey Optional API key for authentication- * @returns Search results or null if the request fails+ * @param context Client context including IP, API key, and client info+ * @returns Search results or error*/export async function searchLibraries(query: string,libraryName: string,- clientIp?: string,- apiKey?: string+ context: ClientContext = {}): Promise<SearchResponse> {try {const url = new URL(`${CONTEXT7_API_BASE_URL}/v2/libs/search`);url.searchParams.set("query", query);url.searchParams.set("libraryName", libraryName);- const headers = generateHeaders(clientIp, apiKey);+ const headers = generateHeaders(context);const response = await fetch(url, { headers });if (!response.ok) {- const errorMessage = await parseErrorResponse(response, apiKey);+ const errorMessage = await parseErrorResponse(response, context.apiKey);console.error(errorMessage);- return {- results: [],- error: errorMessage,- } as SearchResponse;+ return { results: [], error: errorMessage };}const searchData = await response.json();return searchData as SearchResponse;} catch (error) {const errorMessage = `Error searching libraries: ${error}`;console.error(errorMessage);- return { results: [], error: errorMessage } as SearchResponse;+ return { results: [], error: errorMessage };}}/*** Fetches intelligent, reranked context for a natural language query- * @param request The context request parameters (query, topic, library, mode)- * @param clientIp Optional client IP address to include in headers- * @param apiKey Optional API key for authentication+ * @param request The context request parameters (query, libraryId)+ * @param context Client context including IP, API key, and client info* @returns Context response with data*/export async function fetchLibraryContext(request: ContextRequest,- clientIp?: string,- apiKey?: string+ context: ClientContext = {}): Promise<ContextResponse> {try {const url = new URL(`${CONTEXT7_API_BASE_URL}/v2/context`);url.searchParams.set("query", request.query);url.searchParams.set("libraryId", request.libraryId);- const headers = generateHeaders(clientIp, apiKey, { "X-Context7-Source": "mcp-server" });+ const headers = generateHeaders(context);const response = await fetch(url, { headers });if (!response.ok) {- const errorMessage = await parseErrorResponse(response, apiKey);+ const errorMessage = await parseErrorResponse(response, context.apiKey);console.error(errorMessage);return { data: errorMessage };}diff --git a/packages/mcp/src/lib/constants.ts b/packages/mcp/src/lib/constants.tsnew file mode 100644index 00000000..f2cecf19--- /dev/null+++ b/packages/mcp/src/lib/constants.ts@@ -0,0 +1,3 @@+import pkg from "../../package.json" with { type: "json" };++export const SERVER_VERSION: string = pkg.version;diff --git a/packages/mcp/src/lib/encryption.ts b/packages/mcp/src/lib/encryption.tsindex 95410288..96ad64b8 100644--- a/packages/mcp/src/lib/encryption.ts+++ b/packages/mcp/src/lib/encryption.ts@@ -1,4 +1,5 @@import { createCipheriv, randomBytes } from "crypto";+import { SERVER_VERSION } from "./constants.js";const DEFAULT_ENCRYPTION_KEY = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f";const ENCRYPTION_KEY = process.env.CLIENT_IP_ENCRYPTION_KEY || DEFAULT_ENCRYPTION_KEY;@@ -31,17 +32,41 @@ function encryptClientIp(clientIp: string): string {}}-export function generateHeaders(- clientIp?: string,- apiKey?: string,- extraHeaders: Record<string, string> = {}-): Record<string, string> {- const headers: Record<string, string> = { ...extraHeaders };- if (clientIp) {- headers["mcp-client-ip"] = encryptClientIp(clientIp);+export interface ClientContext {+ clientIp?: string;+ apiKey?: string;+ clientInfo?: {+ ide?: string;+ version?: string;+ };+ transport?: "stdio" | "http";+}++/**+ * Generate headers for Context7 API requests.+ * Handles client IP encryption, authentication, and telemetry headers.+ */+export function generateHeaders(context: ClientContext): Record<string, string> {+ const headers: Record<string, string> = {+ "X-Context7-Source": "mcp-server",+ "X-Context7-Server-Version": SERVER_VERSION,+ };++ if (context.clientIp) {+ headers["mcp-client-ip"] = encryptClientIp(context.clientIp);+ }+ if (context.apiKey) {+ headers["Authorization"] = `Bearer ${context.apiKey}`;}- if (apiKey) {- headers["Authorization"] = `Bearer ${apiKey}`;+ if (context.clientInfo?.ide) {+ headers["X-Context7-Client-IDE"] = context.clientInfo.ide;}+ if (context.clientInfo?.version) {+ headers["X-Context7-Client-Version"] = context.clientInfo.version;+ }+ if (context.transport) {+ headers["X-Context7-Transport"] = context.transport;+ }+return headers;}diff --git a/packages/mcp/src/lib/utils.ts b/packages/mcp/src/lib/utils.tsindex 814a4a81..f6c4d721 100644--- a/packages/mcp/src/lib/utils.ts+++ b/packages/mcp/src/lib/utils.ts@@ -67,3 +67,18 @@ export function formatSearchResults(searchResponse: SearchResponse): string {const formattedResults = searchResponse.results.map(formatSearchResult);return formattedResults.join("\n----------\n");}++/**+ * Extract client info from User-Agent header.+ * Parses formats like "Cursor/2.2.44 (darwin arm64)" or "claude-code/2.0.71"+ */+export function extractClientInfoFromUserAgent(+ userAgent: string | undefined+): { ide?: string; version?: string } | undefined {+ if (!userAgent) return undefined;+ const match = userAgent.match(/^([^\/\s]+)\/([^\s(]+)/);+ if (match) {+ return { ide: match[1], version: match[2] };+ }+ return undefined;+}diff --git a/packages/mcp/tsconfig.json b/packages/mcp/tsconfig.jsonindex 624d4ca3..83d8dcb6 100644--- a/packages/mcp/tsconfig.json+++ b/packages/mcp/tsconfig.json@@ -1,8 +1,9 @@{"extends": "../../tsconfig.json","compilerOptions": {- "module": "Node16",- "moduleResolution": "Node16",+ "module": "NodeNext",+ "moduleResolution": "NodeNext",+ "resolveJsonModule": true,"outDir": "./dist","rootDir": "./src"},