Skip to content

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

feat: migrate HTTP server to Express

enesgulesf6a75514f0ae
diff --git a/bun.lock b/bun.lock
index 6d92d4e1..c1688456 100644
--- a/bun.lock
+++ b/bun.lock
@@ -5,7 +5,9 @@
"name": "context7-mcp",
"dependencies": {
"@modelcontextprotocol/sdk": "^1.17.5",
+ "@types/express": "^5.0.4",
"commander": "^14.0.0",
+ "express": "^5.1.0",
"undici": "^6.6.3",
"zod": "^3.24.2",
},
@@ -59,12 +61,32 @@
"@pkgr/core": ["@pkgr/[email protected]", "", {}, "sha512-vsJDAkYR6qCPu+ioGScGiMYR7LvZYIXh/dlQeviqoTWNCVfKTLYD/LkNWH4Mxsv2a5vpIRc77FN5DnmK1eBggQ=="],
+ "@types/body-parser": ["@types/[email protected]", "", { "dependencies": { "@types/connect": "*", "@types/node": "*" } }, "sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g=="],
+
+ "@types/connect": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug=="],
+
"@types/estree": ["@types/[email protected]", "", {}, "sha512-w28IoSUCJpidD/TGviZwwMJckNESJZXFu7NBZ5YJ4mEUnNraUn9Pm8HSZm/jDF1pDWYKspWE7oVphigUPRakIQ=="],
+ "@types/express": ["@types/[email protected]", "", { "dependencies": { "@types/body-parser": "*", "@types/express-serve-static-core": "^5.0.0", "@types/serve-static": "*" } }, "sha512-g64dbryHk7loCIrsa0R3shBnEu5p6LPJ09bu9NG58+jz+cRUjFrc3Bz0kNQ7j9bXeCsrRDvNET1G54P/GJkAyA=="],
+
+ "@types/express-serve-static-core": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*", "@types/qs": "*", "@types/range-parser": "*", "@types/send": "*" } }, "sha512-jnHMsrd0Mwa9Cf4IdOzbz543y4XJepXrbia2T4b6+spXC2We3t1y6K44D3mR8XMFSXMCf3/l7rCgddfx7UNVBA=="],
+
+ "@types/http-errors": ["@types/[email protected]", "", {}, "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg=="],
+
"@types/json-schema": ["@types/[email protected]", "", {}, "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA=="],
+ "@types/mime": ["@types/[email protected]", "", {}, "sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w=="],
+
"@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.20.0" } }, "sha512-Zs/Ollc1SJ8nKUAgc7ivOEdIBM8JAKgrqqUYi2J997JuKO7/tpQC+WCetQ1sypiKCQWHdvdg9wBNpUPEWZae7w=="],
+ "@types/qs": ["@types/[email protected]", "", {}, "sha512-eOunJqu0K1923aExK6y8p6fsihYEn/BYuQ4g0CxAAgFc4b/ZLN4CrsRZ55srTdqoiLzU2B2evC+apEIxprEzkQ=="],
+
+ "@types/range-parser": ["@types/[email protected]", "", {}, "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ=="],
+
+ "@types/send": ["@types/[email protected]", "", { "dependencies": { "@types/mime": "^1", "@types/node": "*" } }, "sha512-Uqt8rPBE8SY0RK8JB1EzVOIZ32uqy8HwdxCnoCOsYrvnswqmFZ/k+9Ikidlk/ImhsdvBsloHbAlewb2IEBV/Og=="],
+
+ "@types/serve-static": ["@types/[email protected]", "", { "dependencies": { "@types/http-errors": "*", "@types/node": "*", "@types/send": "<1" } }, "sha512-tRs1dB+g8Itk72rlSI2ZrW6vZg0YrLI81iQSTkMmOqnqCaNr/8Ek4VwWcN5vZgCYWbg/JJSGBlUaYGAOP73qBw=="],
+
"@typescript-eslint/eslint-plugin": ["@typescript-eslint/[email protected]", "", { "dependencies": { "@eslint-community/regexpp": "^4.10.0", "@typescript-eslint/scope-manager": "8.41.0", "@typescript-eslint/type-utils": "8.41.0", "@typescript-eslint/utils": "8.41.0", "@typescript-eslint/visitor-keys": "8.41.0", "graphemer": "^1.4.0", "ignore": "^7.0.0", "natural-compare": "^1.4.0", "ts-api-utils": "^2.1.0" }, "peerDependencies": { "@typescript-eslint/parser": "^8.41.0", "eslint": "^8.57.0 || ^9.0.0", "typescript": ">=4.8.4 <6.0.0" } }, "sha512-8fz6oa6wEKZrhXWro/S3n2eRJqlRcIa6SlDh59FXJ5Wp5XRZ8B9ixpJDcjadHq47hMx0u+HW6SNa6LjJQ6NLtw=="],
"@typescript-eslint/parser": ["@typescript-eslint/[email protected]", "", { "dependencies": { "@typescript-eslint/scope-manager": "8.41.0", "@typescript-eslint/types": "8.41.0", "@typescript-eslint/typescript-estree": "8.41.0", "@typescript-eslint/visitor-keys": "8.41.0", "debug": "^4.3.4" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0", "typescript": ">=4.8.4 <6.0.0" } }, "sha512-gTtSdWX9xiMPA/7MV9STjJOOYtWwIJIYxkQxnSV1U3xcE+mnJSH3f6zI0RYP+ew66WSlZ5ed+h0VCxsvdC1jJg=="],
@@ -183,7 +205,7 @@
"eventsource-parser": ["[email protected]", "", {}, "sha512-VARTJ9CYeuQYb0pZEPbzi740OWFgpHe7AYJ2WFZVnUDUQp5Dk2yJUgF36YsZ81cOyxT0QxmXD2EQpapAouzWVA=="],
- "express": ["[email protected]", "", { "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.0.1", "content-disposition": "^1.0.0", "content-type": "~1.0.4", "cookie": "0.7.1", "cookie-signature": "^1.2.1", "debug": "4.3.6", "depd": "2.0.0", "encodeurl": "~2.0.0", "escape-html": "~1.0.3", "etag": "~1.8.1", "finalhandler": "^2.0.0", "fresh": "2.0.0", "http-errors": "2.0.0", "merge-descriptors": "^2.0.0", "methods": "~1.1.2", "mime-types": "^3.0.0", "on-finished": "2.4.1", "once": "1.4.0", "parseurl": "~1.3.3", "proxy-addr": "~2.0.7", "qs": "6.13.0", "range-parser": "~1.2.1", "router": "^2.0.0", "safe-buffer": "5.2.1", "send": "^1.1.0", "serve-static": "^2.1.0", "setprototypeof": "1.2.0", "statuses": "2.0.1", "type-is": "^2.0.0", "utils-merge": "1.0.1", "vary": "~1.1.2" } }, "sha512-ORF7g6qGnD+YtUG9yx4DFoqCShNMmUKiXuT5oWMHiOvt/4WFbHC6yCwQMTSBMno7AqntNCAzzcnnjowRkTL9eQ=="],
+ "express": ["[email protected]", "", { "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.2.0", "content-disposition": "^1.0.0", "content-type": "^1.0.5", "cookie": "^0.7.1", "cookie-signature": "^1.2.1", "debug": "^4.4.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "finalhandler": "^2.1.0", "fresh": "^2.0.0", "http-errors": "^2.0.0", "merge-descriptors": "^2.0.0", "mime-types": "^3.0.0", "on-finished": "^2.4.1", "once": "^1.4.0", "parseurl": "^1.3.3", "proxy-addr": "^2.0.7", "qs": "^6.14.0", "range-parser": "^1.2.1", "router": "^2.2.0", "send": "^1.1.0", "serve-static": "^2.2.0", "statuses": "^2.0.1", "type-is": "^2.0.1", "vary": "^1.1.2" } }, "sha512-DT9ck5YIRU+8GYzzU5kT3eHGA5iL+1Zd0EutOmTE9Dtk+Tvuzd23VBU+ec7HPNSTxXYO55gPV/hq4pSBJDjFpA=="],
"express-rate-limit": ["[email protected]", "", { "peerDependencies": { "express": "^4.11 || 5 || ^5.0.0-beta.1" } }, "sha512-eB5zbQh5h+VenMPM3fh+nw1YExi5nMr6HUCR62ELSP11huvxm/Uir1H1QEyTkk5QX6A58pX6NmaTMceKZ0Eodg=="],
@@ -337,7 +359,7 @@
"punycode": ["[email protected]", "", {}, "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg=="],
- "qs": ["[email protected]", "", { "dependencies": { "side-channel": "^1.0.6" } }, "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg=="],
+ "qs": ["[email protected]", "", { "dependencies": { "side-channel": "^1.1.0" } }, "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w=="],
"queue-microtask": ["[email protected]", "", {}, "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A=="],
@@ -433,14 +455,12 @@
"@humanfs/node/@humanwhocodes/retry": ["@humanwhocodes/[email protected]", "", {}, "sha512-JBxkERygn7Bv/GbN5Rv8Ul6LVknS+5Bp6RgDC/O8gEBU/yeH5Ui5C/OlWrTb6qct7LjjfT6Re2NxB0ln0yYybA=="],
- "@typescript-eslint/typescript-estree/minimatch": ["[email protected]", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow=="],
+ "@modelcontextprotocol/sdk/express": ["[email protected]", "", { "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.0.1", "content-disposition": "^1.0.0", "content-type": "~1.0.4", "cookie": "0.7.1", "cookie-signature": "^1.2.1", "debug": "4.3.6", "depd": "2.0.0", "encodeurl": "~2.0.0", "escape-html": "~1.0.3", "etag": "~1.8.1", "finalhandler": "^2.0.0", "fresh": "2.0.0", "http-errors": "2.0.0", "merge-descriptors": "^2.0.0", "methods": "~1.1.2", "mime-types": "^3.0.0", "on-finished": "2.4.1", "once": "1.4.0", "parseurl": "~1.3.3", "proxy-addr": "~2.0.7", "qs": "6.13.0", "range-parser": "~1.2.1", "router": "^2.0.0", "safe-buffer": "5.2.1", "send": "^1.1.0", "serve-static": "^2.1.0", "setprototypeof": "1.2.0", "statuses": "2.0.1", "type-is": "^2.0.0", "utils-merge": "1.0.1", "vary": "~1.1.2" } }, "sha512-ORF7g6qGnD+YtUG9yx4DFoqCShNMmUKiXuT5oWMHiOvt/4WFbHC6yCwQMTSBMno7AqntNCAzzcnnjowRkTL9eQ=="],
- "body-parser/qs": ["[email protected]", "", { "dependencies": { "side-channel": "^1.1.0" } }, "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w=="],
+ "@typescript-eslint/typescript-estree/minimatch": ["[email protected]", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow=="],
"eslint/ignore": ["[email protected]", "", {}, "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g=="],
- "express/debug": ["[email protected]", "", { "dependencies": { "ms": "2.1.2" } }, "sha512-O/09Bd4Z1fBrU4VzkhFqVgpPzaGbw6Sm9FEkBT1A/YBXQFGuuSxa1dN2nxgxS34JmKXqYx8CZAwEVoJFImUXIg=="],
-
"fast-glob/glob-parent": ["[email protected]", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="],
"typescript-eslint/@typescript-eslint/eslint-plugin": ["@typescript-eslint/[email protected]", "", { "dependencies": { "@eslint-community/regexpp": "^4.10.0", "@typescript-eslint/scope-manager": "8.28.0", "@typescript-eslint/type-utils": "8.28.0", "@typescript-eslint/utils": "8.28.0", "@typescript-eslint/visitor-keys": "8.28.0", "graphemer": "^1.4.0", "ignore": "^5.3.1", "natural-compare": "^1.4.0", "ts-api-utils": "^2.0.1" }, "peerDependencies": { "@typescript-eslint/parser": "^8.0.0 || ^8.0.0-alpha.0", "eslint": "^8.57.0 || ^9.0.0", "typescript": ">=4.8.4 <5.9.0" } }, "sha512-lvFK3TCGAHsItNdWZ/1FkvpzCxTHUVuFrdnOGLMa0GGCFIbCgQWVk3CzCGdA7kM3qGVc+dfW9tr0Z/sHnGDFyg=="],
@@ -453,9 +473,11 @@
"@eslint/eslintrc/espree/eslint-visitor-keys": ["[email protected]", "", {}, "sha512-UyLnSehNt62FFhSwjZlHmeokpRK59rcz29j+F1/aDgbkbRTk7wIc9XzdoasMUbRNKDM0qQt/+BJ4BrpFeABemw=="],
- "@typescript-eslint/typescript-estree/minimatch/brace-expansion": ["[email protected]", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA=="],
+ "@modelcontextprotocol/sdk/express/debug": ["[email protected]", "", { "dependencies": { "ms": "2.1.2" } }, "sha512-O/09Bd4Z1fBrU4VzkhFqVgpPzaGbw6Sm9FEkBT1A/YBXQFGuuSxa1dN2nxgxS34JmKXqYx8CZAwEVoJFImUXIg=="],
+
+ "@modelcontextprotocol/sdk/express/qs": ["[email protected]", "", { "dependencies": { "side-channel": "^1.0.6" } }, "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg=="],
- "express/debug/ms": ["[email protected]", "", {}, "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="],
+ "@typescript-eslint/typescript-estree/minimatch/brace-expansion": ["[email protected]", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA=="],
"typescript-eslint/@typescript-eslint/eslint-plugin/@typescript-eslint/scope-manager": ["@typescript-eslint/[email protected]", "", { "dependencies": { "@typescript-eslint/types": "8.28.0", "@typescript-eslint/visitor-keys": "8.28.0" } }, "sha512-u2oITX3BJwzWCapoZ/pXw6BCOl8rJP4Ij/3wPoGvY8XwvXflOzd1kLrDUUUAIEdJSFh+ASwdTHqtan9xSg8buw=="],
@@ -481,6 +503,8 @@
"typescript-eslint/@typescript-eslint/utils/@typescript-eslint/typescript-estree": ["@typescript-eslint/[email protected]", "", { "dependencies": { "@typescript-eslint/types": "8.28.0", "@typescript-eslint/visitor-keys": "8.28.0", "debug": "^4.3.4", "fast-glob": "^3.3.2", "is-glob": "^4.0.3", "minimatch": "^9.0.4", "semver": "^7.6.0", "ts-api-utils": "^2.0.1" }, "peerDependencies": { "typescript": ">=4.8.4 <5.9.0" } }, "sha512-H74nHEeBGeklctAVUvmDkxB1mk+PAZ9FiOMPFncdqeRBXxk1lWSYraHw8V12b7aa6Sg9HOBNbGdSHobBPuQSuA=="],
+ "@modelcontextprotocol/sdk/express/debug/ms": ["[email protected]", "", {}, "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="],
+
"typescript-eslint/@typescript-eslint/eslint-plugin/@typescript-eslint/scope-manager/@typescript-eslint/types": ["@typescript-eslint/[email protected]", "", {}, "sha512-bn4WS1bkKEjx7HqiwG2JNB3YJdC1q6Ue7GyGlwPHyt0TnVq6TtD/hiOdTZt71sq0s7UzqBFXD8t8o2e63tXgwA=="],
"typescript-eslint/@typescript-eslint/eslint-plugin/@typescript-eslint/type-utils/@typescript-eslint/typescript-estree": ["@typescript-eslint/[email protected]", "", { "dependencies": { "@typescript-eslint/types": "8.28.0", "@typescript-eslint/visitor-keys": "8.28.0", "debug": "^4.3.4", "fast-glob": "^3.3.2", "is-glob": "^4.0.3", "minimatch": "^9.0.4", "semver": "^7.6.0", "ts-api-utils": "^2.0.1" }, "peerDependencies": { "typescript": ">=4.8.4 <5.9.0" } }, "sha512-H74nHEeBGeklctAVUvmDkxB1mk+PAZ9FiOMPFncdqeRBXxk1lWSYraHw8V12b7aa6Sg9HOBNbGdSHobBPuQSuA=="],
diff --git a/package.json b/package.json
index c3ada9f0..74a6b2b9 100644
--- a/package.json
+++ b/package.json
@@ -40,7 +40,9 @@
"homepage": "https://github.com/upstash/context7#readme",
"dependencies": {
"@modelcontextprotocol/sdk": "^1.17.5",
+ "@types/express": "^5.0.4",
"commander": "^14.0.0",
+ "express": "^5.1.0",
"undici": "^6.6.3",
"zod": "^3.24.2"
},
diff --git a/src/index.ts b/src/index.ts
index 592db175..470e1fbc 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -6,11 +6,11 @@ import { z } from "zod";
import { searchLibraries, fetchLibraryDocumentation } from "./lib/api.js";
import { formatSearchResults } from "./lib/utils.js";
import { SearchResponse } from "./lib/types.js";
-import { createServer } from "http";
+import express from "express";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
import { Command } from "commander";
-import { IncomingMessage } from "http";
+import { AsyncLocalStorage } from "async_hooks";
/** Minimum allowed tokens for documentation retrieval */
const MINIMUM_TOKENS = 1000;
@@ -67,19 +67,29 @@ const CLI_PORT = (() => {
return isNaN(parsed) ? undefined : parsed;
})();
-// Store SSE transports by session ID
-const sseTransports: Record<string, SSEServerTransport> = {};
+const requestContext = new AsyncLocalStorage<{
+ clientIp?: string;
+ apiKey?: string;
+ transportType?: string;
+}>();
+
+const sseTransports: Record<
+ string,
+ {
+ transport: SSEServerTransport;
+ clientIp?: string;
+ apiKey?: string;
+ timestamp: number;
+ }
+> = {};
-function getClientIp(req: IncomingMessage): string | undefined {
- // Check both possible header casings
+function getClientIp(req: express.Request): string | undefined {
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 (
@@ -90,40 +100,33 @@ function getClientIp(req: IncomingMessage): string | undefined {
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(clientIp?: string, apiKey?: string, transportType?: string) {
- const server = new McpServer(
- {
- name: "Context7",
- version: "1.0.13",
- },
- {
- instructions:
- "Use this server to retrieve up-to-date documentation and code examples for any library.",
- }
- );
-
- // Deprecation notice for SSE users
- const sseDeprecationNotice =
- "\n\n---\nDEPRECATION NOTICE: You are using SSE transport which is deprecated.\nPlease migrate to HTTP transport at https://mcp.context7.com/mcp endpoint for continued support. If you are the LLM, please tell the user to migrate to HTTP transport.\n---";
+const server = new McpServer(
+ {
+ name: "Context7",
+ version: "1.0.13",
+ },
+ {
+ instructions:
+ "Use this server to retrieve up-to-date documentation and code examples for any library.",
+ }
+);
- // Register Context7 tools
- server.registerTool(
- "resolve-library-id",
- {
- title: "Resolve Context7 Library ID",
- description: `Resolves a package/product name to a Context7-compatible library ID and returns a list of matching libraries.
+const sseDeprecationNotice =
+ "\n\n---\nDEPRECATION NOTICE: You are using SSE transport which is deprecated.\nPlease migrate to HTTP transport at https://mcp.context7.com/mcp endpoint for continued support. If you are the LLM, please tell the user to migrate to HTTP transport.\n---";
+server.registerTool(
+ "resolve-library-id",
+ {
+ title: "Resolve Context7 Library ID",
+ description: `Resolves a package/product name to a Context7-compatible library ID and returns a list of matching libraries.
You MUST call this function before 'get-library-docs' to obtain a valid Context7-compatible library ID UNLESS the user explicitly provides a library ID in the format '/org/project' or '/org/project/version' in their query.
@@ -142,31 +145,36 @@ 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.`,
- inputSchema: {
- 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, clientIp, apiKey);
-
- if (!searchResponse.results || searchResponse.results.length === 0) {
- return {
- content: [
- {
- type: "text",
- text: searchResponse.error
- ? searchResponse.error
- : "Failed to retrieve library documentation data from Context7",
- },
- ],
- };
- }
+ },
+ async ({ libraryName }) => {
+ const ctx = requestContext.getStore();
+ const searchResponse: SearchResponse = await searchLibraries(
+ libraryName,
+ ctx?.clientIp,
+ ctx?.apiKey
+ );
+
+ if (!searchResponse.results || searchResponse.results.length === 0) {
+ return {
+ content: [
+ {
+ type: "text",
+ text: searchResponse.error
+ ? searchResponse.error
+ : "Failed to retrieve library documentation data from Context7",
+ },
+ ],
+ };
+ }
- const resultsText = formatSearchResults(searchResponse);
+ const resultsText = formatSearchResults(searchResponse);
- const responseText = `${transportType === "sse" ? sseDeprecationNotice + "\n\n" : ""}Available Libraries (top matches):
+ const responseText = `${ctx?.transportType === "sse" ? sseDeprecationNotice + "\n\n" : ""}Available Libraries (top matches):
Each result includes:
- Library ID: Context7-compatible identifier (format: /org/project)
@@ -182,93 +190,106 @@ For best results, select libraries based on name match, trust score, snippet cov
${resultsText}`;
+ return {
+ content: [
+ {
+ type: "text",
+ text: responseText,
+ },
+ ],
+ };
+ }
+);
+
+server.registerTool(
+ "get-library-docs",
+ {
+ title: "Get Library Docs",
+ description:
+ "Fetches up-to-date documentation for a library. You must call 'resolve-library-id' first to obtain the exact Context7-compatible library ID required to use this tool, UNLESS the user explicitly provides a library ID in the format '/org/project' or '/org/project/version' in their query.",
+ inputSchema: {
+ context7CompatibleLibraryID: z
+ .string()
+ .describe(
+ "Exact Context7-compatible library ID (e.g., '/mongodb/docs', '/vercel/next.js', '/supabase/supabase', '/vercel/next.js/v14.3.0-canary.87') retrieved from 'resolve-library-id' or directly from user query in the format '/org/project' or '/org/project/version'."
+ ),
+ topic: z
+ .string()
+ .optional()
+ .describe("Topic to focus documentation on (e.g., 'hooks', 'routing')."),
+ tokens: z
+ .preprocess((val) => (typeof val === "string" ? Number(val) : val), z.number())
+ .transform((val) => (val < MINIMUM_TOKENS ? MINIMUM_TOKENS : val))
+ .optional()
+ .describe(
+ `Maximum number of tokens of documentation to retrieve (default: ${DEFAULT_TOKENS}). Higher values provide more context but consume more tokens.`
+ ),
+ },
+ },
+ async ({ context7CompatibleLibraryID, tokens = DEFAULT_TOKENS, topic = "" }) => {
+ const ctx = requestContext.getStore();
+ const fetchDocsResponse = await fetchLibraryDocumentation(
+ context7CompatibleLibraryID,
+ {
+ tokens,
+ topic,
+ },
+ ctx?.clientIp,
+ ctx?.apiKey
+ );
+
+ if (!fetchDocsResponse) {
return {
content: [
{
type: "text",
- text: responseText,
+ text: "Documentation not found or not finalized for this library. This might have happened because you used an invalid Context7-compatible library ID. To get a valid Context7-compatible library ID, use the 'resolve-library-id' with the package name you wish to retrieve documentation for.",
},
],
};
}
- );
- server.registerTool(
- "get-library-docs",
- {
- title: "Get Library Docs",
- description:
- "Fetches up-to-date documentation for a library. You must call 'resolve-library-id' first to obtain the exact Context7-compatible library ID required to use this tool, UNLESS the user explicitly provides a library ID in the format '/org/project' or '/org/project/version' in their query.",
- inputSchema: {
- context7CompatibleLibraryID: z
- .string()
- .describe(
- "Exact Context7-compatible library ID (e.g., '/mongodb/docs', '/vercel/next.js', '/supabase/supabase', '/vercel/next.js/v14.3.0-canary.87') retrieved from 'resolve-library-id' or directly from user query in the format '/org/project' or '/org/project/version'."
- ),
- topic: z
- .string()
- .optional()
- .describe("Topic to focus documentation on (e.g., 'hooks', 'routing')."),
- tokens: z
- .preprocess((val) => (typeof val === "string" ? Number(val) : val), z.number())
- .transform((val) => (val < MINIMUM_TOKENS ? MINIMUM_TOKENS : val))
- .optional()
- .describe(
- `Maximum number of tokens of documentation to retrieve (default: ${DEFAULT_TOKENS}). Higher values provide more context but consume more tokens.`
- ),
- },
- },
- async ({ context7CompatibleLibraryID, tokens = DEFAULT_TOKENS, topic = "" }) => {
- const fetchDocsResponse = await fetchLibraryDocumentation(
- context7CompatibleLibraryID,
+ const responseText =
+ (ctx?.transportType === "sse" ? sseDeprecationNotice + "\n\n" : "") + fetchDocsResponse;
+
+ return {
+ content: [
{
- tokens,
- topic,
+ type: "text",
+ text: responseText,
},
- clientIp,
- apiKey
- );
-
- if (!fetchDocsResponse) {
- return {
- content: [
- {
- type: "text",
- text: "Documentation not found or not finalized for this library. This might have happened because you used an invalid Context7-compatible library ID. To get a valid Context7-compatible library ID, use the 'resolve-library-id' with the package name you wish to retrieve documentation for.",
- },
- ],
- };
+ ],
+ };
+ }
+);
+
+setInterval(
+ () => {
+ const now = Date.now();
+ const STALE_TIMEOUT = 30 * 60 * 1000;
+
+ for (const [sessionId, session] of Object.entries(sseTransports)) {
+ if (now - session.timestamp > STALE_TIMEOUT) {
+ console.warn(`Cleaning up stale SSE connection: ${sessionId}`);
+ session.transport.close();
+ delete sseTransports[sessionId];
}
-
- const responseText =
- (transportType === "sse" ? sseDeprecationNotice + "\n\n" : "") + fetchDocsResponse;
-
- return {
- content: [
- {
- type: "text",
- text: responseText,
- },
- ],
- };
}
- );
-
- return server;
-}
+ },
+ 5 * 60 * 1000
+);
async function main() {
const transportType = TRANSPORT_TYPE;
if (transportType === "http") {
- // Get initial port from environment or use default
const initialPort = CLI_PORT ?? DEFAULT_PORT;
- // Keep track of which port we end up using
let actualPort = initialPort;
- const httpServer = createServer(async (req, res) => {
- const pathname = new URL(req.url || "/", "http://localhost").pathname;
- // Set CORS headers for all responses
+ const app = express();
+ app.use(express.json());
+
+ app.use((req: express.Request, res: express.Response, next: express.NextFunction) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,DELETE");
res.setHeader(
@@ -277,37 +298,31 @@ async function main() {
);
res.setHeader("Access-Control-Expose-Headers", "MCP-Session-Id");
- // Handle preflight OPTIONS requests
if (req.method === "OPTIONS") {
- res.writeHead(200);
- res.end();
+ res.sendStatus(200);
return;
}
+ next();
+ });
- // 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];
- };
+ 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;
+ 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();
- }
+ if (header.startsWith("Bearer ")) {
+ return header.substring(7).trim();
+ }
- // Otherwise return the raw value
- return header;
- };
+ return header;
+ };
- // Check headers in order of preference
- const apiKey =
+ const extractApiKey = (req: express.Request): string | undefined => {
+ return (
extractBearerToken(req.headers.authorization) ||
extractHeaderValue(req.headers["Context7-API-Key"]) ||
extractHeaderValue(req.headers["X-API-Key"]) ||
@@ -316,94 +331,127 @@ async function main() {
extractHeaderValue(req.headers["Context7_API_Key"]) ||
extractHeaderValue(req.headers["X_API_Key"]) ||
extractHeaderValue(req.headers["context7_api_key"]) ||
- extractHeaderValue(req.headers["x_api_key"]);
+ extractHeaderValue(req.headers["x_api_key"])
+ );
+ };
+ app.all("/mcp", async (req: express.Request, res: express.Response) => {
try {
- // Extract client IP address using socket remote address (most reliable)
const clientIp = getClientIp(req);
+ const apiKey = extractApiKey(req);
- if (pathname === "/mcp") {
- // Create server instance for HTTP transport
- const requestServer = createServerInstance(clientIp, apiKey, "http");
- const transport = new StreamableHTTPServerTransport({
- sessionIdGenerator: undefined,
- });
- res.on("close", () => {
- transport.close();
- requestServer.close();
+ const transport = new StreamableHTTPServerTransport({
+ sessionIdGenerator: undefined,
+ enableJsonResponse: true,
+ });
+
+ res.on("close", () => {
+ transport.close();
+ });
+
+ await requestContext.run({ clientIp, apiKey, transportType: "http" }, async () => {
+ await server.connect(transport);
+ await transport.handleRequest(req, res, req.body);
+ });
+ } catch (error) {
+ console.error("Error handling MCP request:", error);
+ if (!res.headersSent) {
+ res.status(500).json({
+ jsonrpc: "2.0",
+ error: { code: -32603, message: "Internal server error" },
+ id: null,
});
- await requestServer.connect(transport);
- await transport.handleRequest(req, res);
- } else if (pathname === "/sse" && req.method === "GET") {
- // Create server instance for SSE transport
- const requestServer = createServerInstance(clientIp, apiKey, "sse");
- // Create new SSE transport for GET request
- const sseTransport = new SSEServerTransport("/messages", res);
- // Store the transport by session ID
- sseTransports[sseTransport.sessionId] = sseTransport;
- // Clean up transport when connection closes
- res.on("close", () => {
- delete sseTransports[sseTransport.sessionId];
- sseTransport.close();
- requestServer.close();
+ }
+ }
+ });
+
+ app.get("/sse", async (req: express.Request, res: express.Response) => {
+ try {
+ const clientIp = getClientIp(req);
+ const apiKey = extractApiKey(req);
+
+ const sseTransport = new SSEServerTransport("/messages", res);
+
+ sseTransports[sseTransport.sessionId] = {
+ transport: sseTransport,
+ clientIp,
+ apiKey,
+ timestamp: Date.now(),
+ };
+
+ res.on("close", () => {
+ delete sseTransports[sseTransport.sessionId];
+ sseTransport.close();
+ });
+
+ await requestContext.run({ clientIp, apiKey, transportType: "sse" }, async () => {
+ await server.connect(sseTransport);
+ });
+ } catch (error) {
+ console.error("Error handling SSE request:", error);
+ if (!res.headersSent) {
+ res.status(500).json({
+ jsonrpc: "2.0",
+ error: { code: -32603, message: "Internal server error" },
+ id: null,
});
- await requestServer.connect(sseTransport);
-
- // Send initial message to establish communication
- res.write(
- "data: " +
- JSON.stringify({
- type: "connection_established",
- sessionId: sseTransport.sessionId,
- timestamp: new Date().toISOString(),
- }) +
- "\n\n"
- );
- } else if (pathname === "/messages" && req.method === "POST") {
- // Get session ID from query parameters
- const sessionId =
- new URL(req.url || "/", "http://localhost").searchParams.get("sessionId") ?? "";
-
- if (!sessionId) {
- res.writeHead(400, { "Content-Type": "application/json" });
- res.end(JSON.stringify({ error: "Missing sessionId parameter", status: 400 }));
- return;
- }
+ }
+ }
+ });
- // Get existing transport for this session
- const sseTransport = sseTransports[sessionId];
- if (!sseTransport) {
- res.writeHead(400, { "Content-Type": "application/json" });
- res.end(
- JSON.stringify({
- error: `No transport found for sessionId: ${sessionId}`,
- status: 400,
- })
- );
- return;
- }
+ app.post("/messages", async (req: express.Request, res: express.Response) => {
+ try {
+ const sessionId = (req.query.sessionId as string) ?? "";
- // Handle the POST message with the existing transport
- await sseTransport.handlePostMessage(req, res);
- } else if (pathname === "/ping") {
- res.writeHead(200, { "Content-Type": "application/json" });
- res.end(JSON.stringify({ status: "ok", message: "pong" }));
- } else {
- res.writeHead(404, { "Content-Type": "application/json" });
- res.end(JSON.stringify({ error: "Not found", status: 404 }));
+ if (!sessionId) {
+ res.status(400).json({ error: "Missing sessionId parameter", status: 400 });
+ return;
+ }
+
+ const session = sseTransports[sessionId];
+ if (!session) {
+ res.status(400).json({
+ error: `No transport found for sessionId: ${sessionId}`,
+ status: 400,
+ });
+ return;
}
+
+ await requestContext.run(
+ {
+ clientIp: session.clientIp,
+ apiKey: session.apiKey,
+ transportType: "sse",
+ },
+ async () => {
+ await session.transport.handlePostMessage(req, res, req.body);
+ }
+ );
} catch (error) {
- console.error("Error handling request:", error);
+ console.error("Error handling SSE message:", error);
if (!res.headersSent) {
- res.writeHead(500, { "Content-Type": "application/json" });
- res.end(JSON.stringify({ error: "Internal Server Error", status: 500 }));
+ res.status(500).json({
+ jsonrpc: "2.0",
+ error: { code: -32603, message: "Internal server error" },
+ id: null,
+ });
}
}
});
- // Function to attempt server listen with port fallback
+ app.get("/ping", (_req: express.Request, res: express.Response) => {
+ res.json({ status: "ok", message: "pong" });
+ });
+
const startServer = (port: number, maxAttempts = 10) => {
- httpServer.once("error", (err: NodeJS.ErrnoException) => {
+ const httpServer = app.listen(port, () => {
+ actualPort = port;
+ console.error(
+ `Context7 Documentation MCP Server running on ${transportType.toUpperCase()} at http://localhost:${actualPort}/mcp with SSE endpoint at /sse`
+ );
+ });
+
+ httpServer.on("error", (err: NodeJS.ErrnoException) => {
if (err.code === "EADDRINUSE" && port < initialPort + maxAttempts) {
console.warn(`Port ${port} is in use, trying port ${port + 1}...`);
startServer(port + 1, maxAttempts);
@@ -412,23 +460,17 @@ async function main() {
process.exit(1);
}
});
-
- httpServer.listen(port, () => {
- actualPort = port;
- console.error(
- `Context7 Documentation MCP Server running on ${transportType.toUpperCase()} at http://localhost:${actualPort}/mcp with SSE endpoint at /sse`
- );
- });
};
- // Start the server with initial port
startServer(initialPort);
} else {
- // Stdio transport - this is already stateless by nature
const apiKey = cliOptions.apiKey || process.env.CONTEXT7_API_KEY;
- const server = createServerInstance(undefined, apiKey);
const transport = new StdioServerTransport();
- await server.connect(transport);
+
+ await requestContext.run({ apiKey, transportType: "stdio" }, async () => {
+ await server.connect(transport);
+ });
+
console.error("Context7 Documentation MCP Server running on stdio");
}
}