@upstash/context7-mcp 1.0.34-canary.0 → 1.0.34-canary.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +78 -29
- package/dist/lib/api.js +34 -7
- package/package.json +2 -10
package/dist/index.js
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
3
3
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
4
4
|
import { z } from "zod";
|
|
5
|
-
import { fetchLibraryContext } from "./lib/api.js";
|
|
5
|
+
import { searchLibraries, fetchLibraryContext } from "./lib/api.js";
|
|
6
|
+
import { formatSearchResults } from "./lib/utils.js";
|
|
6
7
|
import express from "express";
|
|
7
8
|
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
8
9
|
import { Command } from "commander";
|
|
@@ -44,29 +45,79 @@ const CLI_PORT = (() => {
|
|
|
44
45
|
const requestContext = new AsyncLocalStorage();
|
|
45
46
|
// Store API key globally for stdio mode (where requestContext may not be available in tool handlers)
|
|
46
47
|
let globalApiKey;
|
|
47
|
-
const stripIpv6Prefix = (ip) => ip.replace(/^::ffff:/, "");
|
|
48
|
-
const isPrivateIp = (ip) => ip.startsWith("10.") || ip.startsWith("192.168.") || /^172\.(1[6-9]|2[0-9]|3[0-1])\./.test(ip);
|
|
49
48
|
function getClientIp(req) {
|
|
50
|
-
const forwardedFor = req.headers["x-forwarded-for"];
|
|
49
|
+
const forwardedFor = req.headers["x-forwarded-for"] || req.headers["X-Forwarded-For"];
|
|
51
50
|
if (forwardedFor) {
|
|
52
51
|
const ips = Array.isArray(forwardedFor) ? forwardedFor[0] : forwardedFor;
|
|
53
|
-
const ipList = ips.split(",").map((ip) =>
|
|
54
|
-
|
|
52
|
+
const ipList = ips.split(",").map((ip) => ip.trim());
|
|
53
|
+
for (const ip of ipList) {
|
|
54
|
+
const plainIp = ip.replace(/^::ffff:/, "");
|
|
55
|
+
if (!plainIp.startsWith("10.") &&
|
|
56
|
+
!plainIp.startsWith("192.168.") &&
|
|
57
|
+
!/^172\.(1[6-9]|2[0-9]|3[0-1])\./.test(plainIp)) {
|
|
58
|
+
return plainIp;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return ipList[0].replace(/^::ffff:/, "");
|
|
62
|
+
}
|
|
63
|
+
if (req.socket?.remoteAddress) {
|
|
64
|
+
return req.socket.remoteAddress.replace(/^::ffff:/, "");
|
|
55
65
|
}
|
|
56
|
-
return
|
|
66
|
+
return undefined;
|
|
57
67
|
}
|
|
58
68
|
const server = new McpServer({
|
|
59
69
|
name: "Context7",
|
|
60
70
|
version: "2.0.0",
|
|
61
71
|
}, {
|
|
62
|
-
capabilities: {
|
|
63
|
-
tools: { listChanged: true },
|
|
64
|
-
},
|
|
65
72
|
instructions: "Use this server to retrieve up-to-date documentation and code examples for any library.",
|
|
66
73
|
});
|
|
67
|
-
server.registerTool("
|
|
68
|
-
title: "
|
|
69
|
-
description: `
|
|
74
|
+
server.registerTool("resolve-library-id", {
|
|
75
|
+
title: "Resolve Context7 Library ID",
|
|
76
|
+
description: `Resolves a package/product name to a Context7-compatible library ID and returns matching libraries.
|
|
77
|
+
|
|
78
|
+
You MUST call this function before 'query-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.
|
|
79
|
+
|
|
80
|
+
Each result includes: Library ID (format: /org/project), name, description, code snippet count, source reputation (High/Medium/Low/Unknown), benchmark score (0-100), and available versions (/org/project/version format).
|
|
81
|
+
|
|
82
|
+
Select the best match based on: name similarity, description relevance, snippet coverage, source reputation, and benchmark score. For ambiguous queries, ask for clarification.`,
|
|
83
|
+
inputSchema: {
|
|
84
|
+
query: z
|
|
85
|
+
.string()
|
|
86
|
+
.describe("The user's original question or task. This is used to rank library results by relevance to what the user is trying to accomplish. IMPORTANT: Do not include any sensitive or confidential information such as API keys, passwords, credentials, or personal data in your query."),
|
|
87
|
+
libraryName: z
|
|
88
|
+
.string()
|
|
89
|
+
.describe("Library name to search for and retrieve a Context7-compatible library ID."),
|
|
90
|
+
},
|
|
91
|
+
}, async ({ query, libraryName }) => {
|
|
92
|
+
const ctx = requestContext.getStore();
|
|
93
|
+
const apiKey = ctx?.apiKey || globalApiKey;
|
|
94
|
+
const searchResponse = await searchLibraries(query, libraryName, ctx?.clientIp, apiKey);
|
|
95
|
+
if (!searchResponse.results || searchResponse.results.length === 0) {
|
|
96
|
+
return {
|
|
97
|
+
content: [
|
|
98
|
+
{
|
|
99
|
+
type: "text",
|
|
100
|
+
text: searchResponse.error
|
|
101
|
+
? searchResponse.error
|
|
102
|
+
: "No libraries found matching the provided name.",
|
|
103
|
+
},
|
|
104
|
+
],
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
return {
|
|
108
|
+
content: [
|
|
109
|
+
{
|
|
110
|
+
type: "text",
|
|
111
|
+
text: formatSearchResults(searchResponse),
|
|
112
|
+
},
|
|
113
|
+
],
|
|
114
|
+
};
|
|
115
|
+
});
|
|
116
|
+
server.registerTool("query-docs", {
|
|
117
|
+
title: "Query Documentation",
|
|
118
|
+
description: `Retrieves and queries up-to-date documentation and code examples from Context7 for any programming library or framework.
|
|
119
|
+
|
|
120
|
+
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.
|
|
70
121
|
|
|
71
122
|
USE THIS TOOL TO:
|
|
72
123
|
- Get current, accurate documentation for libraries (e.g., React, Next.js, Express, LangChain)
|
|
@@ -77,24 +128,14 @@ USE THIS TOOL TO:
|
|
|
77
128
|
query: z
|
|
78
129
|
.string()
|
|
79
130
|
.describe("The question or task you need help with. Be specific and include relevant details. Good: 'How to set up authentication with JWT in Express.js' or 'React useEffect cleanup function examples'. Bad: 'auth' or 'hooks'. IMPORTANT: Do not include any sensitive or confidential information such as API keys, passwords, credentials, or personal data in your query."),
|
|
80
|
-
|
|
81
|
-
.string()
|
|
82
|
-
.optional()
|
|
83
|
-
.describe("Library or framework name (e.g., 'react', 'express') OR exact library ID if provided by the user with or without version (e.g., '/vercel/next.js', '/vercel/next.js@v14.3.0-canary.87'). If omitted, auto-selects based on query."),
|
|
84
|
-
topic: z
|
|
131
|
+
libraryId: z
|
|
85
132
|
.string()
|
|
86
|
-
.
|
|
87
|
-
.describe("Narrow down results to a specific topic within the library. Examples: 'hooks', 'routing', 'middleware', 'authentication', 'state management'."),
|
|
88
|
-
mode: z
|
|
89
|
-
.enum(["code", "info"])
|
|
90
|
-
.optional()
|
|
91
|
-
.default("code")
|
|
92
|
-
.describe("Type of content to prioritize. Use 'code' (default) when you need working code examples, API usage patterns, and implementation snippets. Use 'info' when you need conceptual narrative explanations, architectural overviews, or understanding how something works."),
|
|
133
|
+
.describe("Context7-compatible library ID (e.g., '/mongodb/docs' or '/vercel/next.js'). Retrieved from 'resolve-library-id' or directly from user query in the format '/org/project' or '/org/project/version'."),
|
|
93
134
|
},
|
|
94
|
-
}, async ({ query,
|
|
135
|
+
}, async ({ query, libraryId }) => {
|
|
95
136
|
const ctx = requestContext.getStore();
|
|
96
137
|
const apiKey = ctx?.apiKey || globalApiKey;
|
|
97
|
-
const response = await fetchLibraryContext({ query,
|
|
138
|
+
const response = await fetchLibraryContext({ query, libraryId }, ctx?.clientIp, apiKey);
|
|
98
139
|
return {
|
|
99
140
|
content: [
|
|
100
141
|
{
|
|
@@ -108,6 +149,7 @@ async function main() {
|
|
|
108
149
|
const transportType = TRANSPORT_TYPE;
|
|
109
150
|
if (transportType === "http") {
|
|
110
151
|
const initialPort = CLI_PORT ?? DEFAULT_PORT;
|
|
152
|
+
let actualPort = initialPort;
|
|
111
153
|
const app = express();
|
|
112
154
|
app.use(express.json());
|
|
113
155
|
app.use((req, res, next) => {
|
|
@@ -137,8 +179,14 @@ async function main() {
|
|
|
137
179
|
};
|
|
138
180
|
const extractApiKey = (req) => {
|
|
139
181
|
return (extractBearerToken(req.headers.authorization) ||
|
|
182
|
+
extractHeaderValue(req.headers["Context7-API-Key"]) ||
|
|
183
|
+
extractHeaderValue(req.headers["X-API-Key"]) ||
|
|
140
184
|
extractHeaderValue(req.headers["context7-api-key"]) ||
|
|
141
|
-
extractHeaderValue(req.headers["x-api-key"])
|
|
185
|
+
extractHeaderValue(req.headers["x-api-key"]) ||
|
|
186
|
+
extractHeaderValue(req.headers["Context7_API_Key"]) ||
|
|
187
|
+
extractHeaderValue(req.headers["X_API_Key"]) ||
|
|
188
|
+
extractHeaderValue(req.headers["context7_api_key"]) ||
|
|
189
|
+
extractHeaderValue(req.headers["x_api_key"]));
|
|
142
190
|
};
|
|
143
191
|
app.all("/mcp", async (req, res) => {
|
|
144
192
|
try {
|
|
@@ -190,7 +238,8 @@ async function main() {
|
|
|
190
238
|
}
|
|
191
239
|
});
|
|
192
240
|
httpServer.once("listening", () => {
|
|
193
|
-
|
|
241
|
+
actualPort = port;
|
|
242
|
+
console.error(`Context7 Documentation MCP Server running on HTTP at http://localhost:${actualPort}/mcp`);
|
|
194
243
|
});
|
|
195
244
|
};
|
|
196
245
|
startServer(initialPort);
|
package/dist/lib/api.js
CHANGED
|
@@ -26,7 +26,7 @@ async function parseErrorResponse(response, apiKey) {
|
|
|
26
26
|
: "Rate limited or quota exceeded. Create a free API key at https://context7.com/dashboard for higher limits.";
|
|
27
27
|
}
|
|
28
28
|
if (status === 404) {
|
|
29
|
-
return "
|
|
29
|
+
return "The library you are trying to access does not exist. Please try with a different library ID.";
|
|
30
30
|
}
|
|
31
31
|
if (status === 401) {
|
|
32
32
|
return "Invalid API key. Please check your API key. API keys should start with 'ctx7sk' prefix.";
|
|
@@ -52,6 +52,38 @@ if (PROXY_URL && !PROXY_URL.startsWith("$") && /^(http|https):\/\//i.test(PROXY_
|
|
|
52
52
|
console.error(`[Context7] Failed to configure proxy agent for provided proxy URL: ${PROXY_URL}:`, error);
|
|
53
53
|
}
|
|
54
54
|
}
|
|
55
|
+
/**
|
|
56
|
+
* Searches for libraries matching the given query
|
|
57
|
+
* @param query The user's question or task (used for LLM relevance ranking)
|
|
58
|
+
* @param libraryName The library name to search for in the database
|
|
59
|
+
* @param clientIp Optional client IP address to include in headers
|
|
60
|
+
* @param apiKey Optional API key for authentication
|
|
61
|
+
* @returns Search results or null if the request fails
|
|
62
|
+
*/
|
|
63
|
+
export async function searchLibraries(query, libraryName, clientIp, apiKey) {
|
|
64
|
+
try {
|
|
65
|
+
const url = new URL(`${CONTEXT7_API_BASE_URL}/v2/libs/search`);
|
|
66
|
+
url.searchParams.set("query", query);
|
|
67
|
+
url.searchParams.set("libraryName", libraryName);
|
|
68
|
+
const headers = generateHeaders(clientIp, apiKey);
|
|
69
|
+
const response = await fetch(url, { headers });
|
|
70
|
+
if (!response.ok) {
|
|
71
|
+
const errorMessage = await parseErrorResponse(response, apiKey);
|
|
72
|
+
console.error(errorMessage);
|
|
73
|
+
return {
|
|
74
|
+
results: [],
|
|
75
|
+
error: errorMessage,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
const searchData = await response.json();
|
|
79
|
+
return searchData;
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
const errorMessage = `Error searching libraries: ${error}`;
|
|
83
|
+
console.error(errorMessage);
|
|
84
|
+
return { results: [], error: errorMessage };
|
|
85
|
+
}
|
|
86
|
+
}
|
|
55
87
|
/**
|
|
56
88
|
* Fetches intelligent, reranked context for a natural language query
|
|
57
89
|
* @param request The context request parameters (query, topic, library, mode)
|
|
@@ -63,12 +95,7 @@ export async function fetchLibraryContext(request, clientIp, apiKey) {
|
|
|
63
95
|
try {
|
|
64
96
|
const url = new URL(`${CONTEXT7_API_BASE_URL}/v2/context`);
|
|
65
97
|
url.searchParams.set("query", request.query);
|
|
66
|
-
|
|
67
|
-
url.searchParams.set("topic", request.topic);
|
|
68
|
-
if (request.library)
|
|
69
|
-
url.searchParams.set("library", request.library);
|
|
70
|
-
if (request.mode)
|
|
71
|
-
url.searchParams.set("mode", request.mode);
|
|
98
|
+
url.searchParams.set("libraryId", request.libraryId);
|
|
72
99
|
const headers = generateHeaders(clientIp, apiKey, { "X-Context7-Source": "mcp-server" });
|
|
73
100
|
const response = await fetch(url, { headers });
|
|
74
101
|
if (!response.ok) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@upstash/context7-mcp",
|
|
3
|
-
"version": "1.0.34-canary.
|
|
3
|
+
"version": "1.0.34-canary.2",
|
|
4
4
|
"mcpName": "io.github.upstash/context7",
|
|
5
5
|
"description": "MCP server for Context7",
|
|
6
6
|
"repository": {
|
|
@@ -41,13 +41,7 @@
|
|
|
41
41
|
"zod": "^3.24.2"
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
|
-
"@ai-sdk/anthropic": "^1.2.12",
|
|
45
|
-
"@ai-sdk/google": "^1.2.7",
|
|
46
|
-
"@ai-sdk/mcp": "^0.2.0",
|
|
47
|
-
"@ai-sdk/openai": "^1.3.22",
|
|
48
44
|
"@types/node": "^22.13.14",
|
|
49
|
-
"ai": "^4.3.16",
|
|
50
|
-
"dotenv": "^16.5.0",
|
|
51
45
|
"typescript": "^5.8.2"
|
|
52
46
|
},
|
|
53
47
|
"scripts": {
|
|
@@ -60,8 +54,6 @@
|
|
|
60
54
|
"format:check": "prettier --check .",
|
|
61
55
|
"dev": "tsc --watch",
|
|
62
56
|
"start": "node dist/index.js --transport http",
|
|
63
|
-
"pack-mcpb": "pnpm install && pnpm run build && rm -rf node_modules && pnpm install --prod && mv mcpb/.mcpbignore .mcpbignore && mv mcpb/manifest.json manifest.json && mv public/icon.png icon.png && mcpb validate manifest.json && mcpb pack . mcpb/context7.mcpb && mv manifest.json mcpb/manifest.json && mv .mcpbignore mcpb/.mcpbignore && mv icon.png public/icon.png && bun install"
|
|
64
|
-
"run-benchmark": "pnpm run build && node dist/benchmark/run-benchmark.js",
|
|
65
|
-
"compare-benchmark": "pnpm run build && node dist/benchmark/compare-benchmark.js"
|
|
57
|
+
"pack-mcpb": "pnpm install && pnpm run build && rm -rf node_modules && pnpm install --prod && mv mcpb/.mcpbignore .mcpbignore && mv mcpb/manifest.json manifest.json && mv public/icon.png icon.png && mcpb validate manifest.json && mcpb pack . mcpb/context7.mcpb && mv manifest.json mcpb/manifest.json && mv .mcpbignore mcpb/.mcpbignore && mv icon.png public/icon.png && bun install"
|
|
66
58
|
}
|
|
67
59
|
}
|