Skip to content

Context7 Platform -- Up-to-date docs for AI agents

Merge remote-tracking branch 'origin/master' into feat/refactor-mcp-usage

enesgules00ee0c7936d4
diff --cc src/index.ts
index d9a88bf1,d4579bdc..c6f85342
--- a/src/index.ts
+++ b/src/index.ts
@@@ -48,8 -47,39 +49,39 @@@ const CLI_PORT = (() =>
// Store SSE transports by session ID
const sseTransports: Record<string, SSEServerTransport> = {};
+ function getClientIp(req: IncomingMessage): string | undefined {
+ // Check both possible header casings
+ const forwardedFor = req.headers["x-forwarded-for"] || req.headers["X-Forwarded-For"];
+
+ if (forwardedFor) {
+ // X-Forwarded-For can contain multiple IPs
+ const ips = Array.isArray(forwardedFor) ? forwardedFor[0] : forwardedFor;
+ const ipList = ips.split(",").map((ip) => ip.trim());
+
+ // Find the first public IP address
+ for (const ip of ipList) {
+ const plainIp = ip.replace(/^::ffff:/, "");
+ if (
+ !plainIp.startsWith("10.") &&
+ !plainIp.startsWith("192.168.") &&
+ !/^172\.(1[6-9]|2[0-9]|3[0-1])\./.test(plainIp)
+ ) {
+ return plainIp;
+ }
+ }
+ // If all are private, use the first one
+ return ipList[0].replace(/^::ffff:/, "");
+ }
+
+ // Fallback: use remote address, strip IPv6-mapped IPv4
+ if (req.socket?.remoteAddress) {
+ return req.socket.remoteAddress.replace(/^::ffff:/, "");
+ }
+ return undefined;
+ }
+
// Function to create a new server instance with all tools registered
- function createServerInstance(apiKey?: string) {
-function createServerInstance(clientIp?: string) {
++function createServerInstance(clientIp?: string, apiKey?: string) {
const server = new McpServer(
{
name: "Context7",
@@@ -85,14 -113,13 +117,14 @@@ Response Format
- If no good matches exist, clearly state this and suggest query refinements
For ambiguous queries, request clarification before proceeding with a best-guess match.`,
- {
- libraryName: z
- .string()
- .describe("Library name to search for and retrieve a Context7-compatible library ID."),
+ inputSchema: {
+ libraryName: z
+ .string()
+ .describe("Library name to search for and retrieve a Context7-compatible library ID."),
+ },
},
async ({ libraryName }) => {
- const searchResponse: SearchResponse = await searchLibraries(libraryName, apiKey);
- const searchResponse: SearchResponse = await searchLibraries(libraryName, clientIp);
++ const searchResponse: SearchResponse = await searchLibraries(libraryName, clientIp, apiKey);
if (!searchResponse.results || searchResponse.results.length === 0) {
return {
@@@ -166,7 -189,7 +198,8 @@@ ${resultsText}`
tokens,
topic,
},
- clientIp
++ clientIp,
+ apiKey
);
if (!fetchDocsResponse) {
@@@ -210,8 -233,9 +243,9 @@@ async function main()
res.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,DELETE");
res.setHeader(
"Access-Control-Allow-Headers",
- "Content-Type, MCP-Session-Id, mcp-session-id, X-Context7-API-Key, context7-api-key, context7_api_key, x-api-key, Authorization"
- "Content-Type, MCP-Session-Id, mcp-session-id, MCP-Protocol-Version"
++ "Content-Type, MCP-Session-Id, MCP-Protocol-Version, X-Context7-API-Key, Context7-API-Key, X-API-Key, Authorization"
);
+ res.setHeader("Access-Control-Expose-Headers", "MCP-Session-Id");
// Handle preflight OPTIONS requests
if (req.method === "OPTIONS") {
@@@ -220,39 -244,12 +254,42 @@@
return;
}
+ // Function to extract header value safely, handling both string and string[] cases
+ const extractHeaderValue = (value: string | string[] | undefined): string | undefined => {
+ if (!value) return undefined;
+ return typeof value === "string" ? value : value[0];
+ };
+
+ // Extract Authorization header and remove Bearer prefix if present
+ const extractBearerToken = (
+ authHeader: string | string[] | undefined
+ ): string | undefined => {
+ const header = extractHeaderValue(authHeader);
+ if (!header) return undefined;
+
+ // If it starts with 'Bearer ', remove that prefix
+ if (header.startsWith("Bearer ")) {
+ return header.substring(7).trim();
+ }
+
+ // Otherwise return the raw value
+ return header;
+ };
+
+ // Check headers in order of preference
+ const apiKey =
+ extractBearerToken(req.headers.authorization) ||
+ extractHeaderValue(req.headers["x-context7-api-key"]) || // Standard with x- prefix
+ extractHeaderValue(req.headers["context7-api-key"]) || // Without x- prefix
+ extractHeaderValue(req.headers["context7_api_key"]) || // With underscores
+ extractHeaderValue(req.headers["x-api-key"]); // Generic API key header
+
try {
+ // Extract client IP address using socket remote address (most reliable)
+ const clientIp = getClientIp(req);
+
// Create new server instance for each request
- const requestServer = createServerInstance(apiKey);
- const requestServer = createServerInstance(clientIp);
++ const requestServer = createServerInstance(clientIp, apiKey);
if (url === "/mcp") {
const transport = new StreamableHTTPServerTransport({
diff --cc src/lib/api.ts
index 6522f51e,208cafab..bd6a363e
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@@ -1,23 -1,21 +1,29 @@@
import { SearchResponse } from "./types.js";
+ import { generateHeaders } from "./encryption.js";
-const CONTEXT7_API_BASE_URL = "https://context7.com/api";
+const CONTEXT7_API_BASE_URL = "http://localhost:3000/api";
const DEFAULT_TYPE = "txt";
/**
* Searches for libraries matching the given query
* @param query The search query
+ * @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
*/
- export async function searchLibraries(query: string, apiKey?: string): Promise<SearchResponse> {
-export async function searchLibraries(query: string, clientIp?: string): Promise<SearchResponse> {
++export async function searchLibraries(
++ query: string,
++ clientIp?: string,
++ apiKey?: string
++): Promise<SearchResponse> {
try {
const url = new URL(`${CONTEXT7_API_BASE_URL}/v1/search`);
url.searchParams.set("query", query);
- const headers: Record<string, string> = {};
+ const headers = generateHeaders(clientIp);
+ if (apiKey) {
+ headers["Authorization"] = `Bearer ${apiKey}`;
+ }
const response = await fetch(url, { headers });
if (!response.ok) {
@@@ -46,7 -44,7 +52,8 @@@
* Fetches documentation context for a specific library
* @param libraryId The library ID to fetch documentation for
* @param options Options for the request
+ * @param clientIp Optional client IP address to include in headers
+ * @param apiKey Optional API key for authentication
* @returns The documentation text or null if the request fails
*/
export async function fetchLibraryDocumentation(
@@@ -55,7 -53,7 +62,8 @@@
tokens?: number;
topic?: string;
} = {},
- clientIp?: string
++ clientIp?: string,
+ apiKey?: string
): Promise<string | null> {
try {
if (libraryId.startsWith("/")) {
@@@ -66,12 -64,7 +74,10 @@@
if (options.topic) url.searchParams.set("topic", options.topic);
url.searchParams.set("type", DEFAULT_TYPE);
- const headers: Record<string, string> = {
- "X-Context7-Source": "mcp-server",
- };
+ const headers = generateHeaders(clientIp, { "X-Context7-Source": "mcp-server" });
+ if (apiKey) {
+ headers["Authorization"] = `Bearer ${apiKey}`;
+ }
const response = await fetch(url, { headers });
if (!response.ok) {