@mirsella/context7-account-broker 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mirsella
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,216 @@
1
+ # Context7 Account Broker
2
+
3
+ [![CI](https://github.com/mirsella/context7-account-broker/actions/workflows/ci.yml/badge.svg)](https://github.com/mirsella/context7-account-broker/actions/workflows/ci.yml)
4
+ [![Node.js 20+](https://img.shields.io/badge/Node.js-20%2B-339933?logo=node.js&logoColor=white)](https://nodejs.org/)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
6
+
7
+ A drop-in Context7 MCP proxy for people who use more than one authorized API
8
+ key. It balances requests by quota usage, keeps each library on the same account,
9
+ and caches successful responses on disk.
10
+
11
+ OpenCode sees the standard Context7 tools:
12
+
13
+ - `resolve-library-id`
14
+ - `query-docs`
15
+
16
+ The broker handles account selection, failover, caching, and quota refreshes
17
+ without changing tool schemas or results.
18
+
19
+ ## What it does
20
+
21
+ - Routes new work to the account with the lowest proportional quota usage.
22
+ - Keeps a library on the same account within each project.
23
+ - Fails over when an account is blocked, rate limited, unauthorized, or
24
+ temporarily unreachable.
25
+ - Reads Context7's `RateLimit-*` headers instead of estimating quota locally.
26
+ - Caches exact successful calls for 30 days by default.
27
+ - Coalesces concurrent identical requests into one upstream call.
28
+ - Stores named credentials in a private `0600` configuration file.
29
+ - Provides CLI commands for account management, quota status, and diagnostics.
30
+
31
+ ## Quick start
32
+
33
+ ### 1. Add your Context7 accounts
34
+
35
+ The command prompts for the API key without displaying it:
36
+
37
+ ```bash
38
+ npx -y @mirsella/context7-account-broker accounts add personal
39
+ ```
40
+
41
+ Repeat the command with a different name for each account. To verify the saved
42
+ accounts without exposing their keys:
43
+
44
+ ```bash
45
+ npx -y @mirsella/context7-account-broker accounts list
46
+ ```
47
+
48
+ ### 2. Configure OpenCode
49
+
50
+ Add the server to `~/.config/opencode/opencode.jsonc`:
51
+
52
+ ```jsonc
53
+ {
54
+ "mcp": {
55
+ "context7": {
56
+ "type": "local",
57
+ "command": ["npx", "-y", "@mirsella/context7-account-broker"],
58
+ "timeout": 30000,
59
+ "enabled": true
60
+ }
61
+ }
62
+ }
63
+ ```
64
+
65
+ Restart OpenCode, then check the connection:
66
+
67
+ ```bash
68
+ opencode mcp list
69
+ ```
70
+
71
+ The package is published to npm, so no Git checkout or local build is required.
72
+
73
+ ## CLI
74
+
75
+ The examples below use the published npm package.
76
+
77
+ | Command | Purpose |
78
+ | --- | --- |
79
+ | `accounts add [name]` | Add a named API key using a hidden prompt or stdin |
80
+ | `accounts list` | List account names, sources, and key fingerprints |
81
+ | `accounts remove <name>` | Remove a file-configured account |
82
+ | `status` | Fetch current quota usage and reset times |
83
+ | `config` | Print effective paths and runtime settings |
84
+ | `help` | Show command help |
85
+ | `serve` | Start the stdio MCP server (the default) |
86
+
87
+ For example:
88
+
89
+ ```bash
90
+ BROKER=@mirsella/context7-account-broker
91
+
92
+ npx -y "$BROKER" status
93
+ npx -y "$BROKER" config
94
+ npx -y "$BROKER" accounts remove personal
95
+ ```
96
+
97
+ For non-interactive account setup:
98
+
99
+ ```bash
100
+ BROKER=@mirsella/context7-account-broker
101
+ printf '%s\n' "$CONTEXT7_API_KEY" |
102
+ npx -y "$BROKER" accounts add personal
103
+ ```
104
+
105
+ ## Account selection
106
+
107
+ At startup, the broker probes each key and reads Context7's authoritative
108
+ `RateLimit-Limit`, `RateLimit-Remaining`, and `RateLimit-Reset` headers.
109
+
110
+ For a library without an existing assignment, it chooses the available account
111
+ with the lowest proportional usage:
112
+
113
+ ```text
114
+ used / limit = (limit - remaining) / limit
115
+ ```
116
+
117
+ Equal accounts rotate in round-robin order. Once selected, the account is saved
118
+ as the preferred account for that library and project. A temporary failure can
119
+ move one request elsewhere without discarding the preference.
120
+
121
+ Blocked accounts are checked again at their reset time. Free-plan accounts are
122
+ also checked at the next UTC day so Context7's daily bonus calls can become
123
+ available.
124
+
125
+ ## Cache
126
+
127
+ Successful tool results are cached by:
128
+
129
+ - project scope
130
+ - tool name
131
+ - canonicalized arguments
132
+ - API-key hash
133
+
134
+ The API-key partition prevents a removed account from serving its cached private
135
+ content. Expired files are removed on startup and lazily when read. Concurrent
136
+ identical calls share one in-flight request.
137
+
138
+ The default cache directory is:
139
+
140
+ ```text
141
+ ~/.cache/context7-account-broker
142
+ ```
143
+
144
+ Delete that directory to invalidate all cached results and affinities.
145
+
146
+ ## Credentials
147
+
148
+ Named accounts are stored at:
149
+
150
+ ```text
151
+ ~/.config/context7-account-broker/accounts.json
152
+ ```
153
+
154
+ The directory uses mode `0700` and the file uses mode `0600`.
155
+
156
+ When this file contains accounts, it acts as an allowlist. Inherited
157
+ `CONTEXT7_API_KEY` and `CONTEXT7_API_KEYS` values are ignored unless
158
+ `CONTEXT7_BROKER_INCLUDE_ENV=1` is set. This prevents an unrelated shell key from
159
+ silently joining a configured pool.
160
+
161
+ With no configured account file, the broker accepts:
162
+
163
+ ```bash
164
+ export CONTEXT7_API_KEYS='ctx7sk_first,ctx7sk_second'
165
+ ```
166
+
167
+ ## Configuration
168
+
169
+ | Environment variable | Default | Description |
170
+ | --- | --- | --- |
171
+ | `CONTEXT7_API_KEY` | unset | One API key when no account file is configured |
172
+ | `CONTEXT7_API_KEYS` | unset | Separated API keys |
173
+ | `CONTEXT7_BROKER_CONFIG` | XDG config path | Override the accounts file path |
174
+ | `CONTEXT7_BROKER_INCLUDE_ENV` | unset | Include environment keys with `1` |
175
+ | `CONTEXT7_MCP_URL` | `https://mcp.context7.com/mcp` | Upstream MCP endpoint |
176
+ | `CONTEXT7_ACCOUNT_COOLDOWN_MS` | `30000` | Transient failure cooldown |
177
+ | `CONTEXT7_CACHE_TTL_DAYS` | `30` | Result and affinity cache lifetime |
178
+ | `CONTEXT7_CACHE_DIR` | XDG cache path | Override the cache directory |
179
+ | `CONTEXT7_PROJECT_ID` | current directory | Cache and affinity scope |
180
+
181
+ ## Quota cost
182
+
183
+ Context7 attaches quota state to normal API responses rather than exposing a
184
+ free status endpoint. Each startup probe, refresh, and `status` check consumes
185
+ one API request per checked account.
186
+
187
+ ## Development
188
+
189
+ Requirements: Node.js 20 or newer and pnpm.
190
+
191
+ ```bash
192
+ git clone https://github.com/mirsella/context7-account-broker.git
193
+ cd context7-account-broker
194
+ pnpm install
195
+ pnpm typecheck
196
+ pnpm test
197
+ pnpm build
198
+ ```
199
+
200
+ Run the local binary:
201
+
202
+ ```bash
203
+ node dist/index.js accounts list
204
+ node dist/index.js status
205
+ node dist/index.js serve
206
+ ```
207
+
208
+ ## Responsible use
209
+
210
+ Use API keys only for accounts you own or are authorized to aggregate. Follow
211
+ Context7's terms and plan limits. The broker does not create accounts, bypass
212
+ authentication, or hide upstream failures.
213
+
214
+ ## License
215
+
216
+ [MIT](LICENSE)
package/dist/cache.js ADDED
@@ -0,0 +1,106 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { isCallToolResult } from "@modelcontextprotocol/server";
5
+ function canonicalJson(value) {
6
+ if (Array.isArray(value))
7
+ return `[${value.map(canonicalJson).join(",")}]`;
8
+ if (value === null || typeof value !== "object")
9
+ return JSON.stringify(value) ?? "null";
10
+ return `{${Object.entries(value)
11
+ .sort(([a], [b]) => a.localeCompare(b))
12
+ .map(([key, item]) => `${JSON.stringify(key)}:${canonicalJson(item)}`)
13
+ .join(",")}}`;
14
+ }
15
+ function digest(value) {
16
+ return createHash("sha256").update(canonicalJson(value)).digest("hex");
17
+ }
18
+ export class ResultCache {
19
+ ttlMs;
20
+ resultsDirectory;
21
+ affinityDirectory;
22
+ constructor(directory, ttlMs) {
23
+ this.ttlMs = ttlMs;
24
+ this.resultsDirectory = join(directory, "results");
25
+ this.affinityDirectory = join(directory, "affinity");
26
+ }
27
+ static async open(directory, ttlMs) {
28
+ const cache = new ResultCache(directory, ttlMs);
29
+ await Promise.all([
30
+ mkdir(cache.resultsDirectory, { recursive: true, mode: 0o700 }),
31
+ mkdir(cache.affinityDirectory, { recursive: true, mode: 0o700 }),
32
+ ]);
33
+ await Promise.all([
34
+ cache.removeExpired(cache.resultsDirectory),
35
+ cache.removeExpired(cache.affinityDirectory),
36
+ ]);
37
+ return cache;
38
+ }
39
+ requestKey(scope, tool, args) {
40
+ return digest({ version: 1, scope, tool, args: args ?? {} });
41
+ }
42
+ async getResult(requestKey, accountKey) {
43
+ const entry = await this.read(join(this.resultsDirectory, `${requestKey}-${accountKey}.json`));
44
+ if (!entry || !isCallToolResult(entry.result))
45
+ return undefined;
46
+ return entry.result;
47
+ }
48
+ setResult(requestKey, accountKey, result) {
49
+ return this.write(join(this.resultsDirectory, `${requestKey}-${accountKey}.json`), {
50
+ expiresAt: Date.now() + this.ttlMs,
51
+ result,
52
+ });
53
+ }
54
+ async getAffinity(scope, library) {
55
+ const entry = await this.read(join(this.affinityDirectory, `${digest({ version: 1, scope, library })}.json`));
56
+ return typeof entry?.accountKey === "string" ? entry.accountKey : undefined;
57
+ }
58
+ setAffinity(scope, library, accountKey) {
59
+ return this.write(join(this.affinityDirectory, `${digest({ version: 1, scope, library })}.json`), {
60
+ expiresAt: Date.now() + this.ttlMs,
61
+ accountKey,
62
+ });
63
+ }
64
+ async read(file) {
65
+ try {
66
+ const entry = JSON.parse(await readFile(file, "utf8"));
67
+ if (!Number.isFinite(entry.expiresAt) || entry.expiresAt <= Date.now()) {
68
+ await unlink(file).catch(() => undefined);
69
+ return undefined;
70
+ }
71
+ return entry;
72
+ }
73
+ catch (error) {
74
+ if (error.code === "ENOENT")
75
+ return undefined;
76
+ console.warn(`[context7-account-broker] Ignoring invalid cache entry ${file}: ${String(error)}`);
77
+ await unlink(file).catch(() => undefined);
78
+ return undefined;
79
+ }
80
+ }
81
+ async write(file, value) {
82
+ const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;
83
+ try {
84
+ await writeFile(temporary, JSON.stringify(value), { mode: 0o600 });
85
+ await rename(temporary, file);
86
+ }
87
+ finally {
88
+ await unlink(temporary).catch(() => undefined);
89
+ }
90
+ }
91
+ async removeExpired(directory) {
92
+ const cutoff = Date.now() - this.ttlMs;
93
+ const files = await readdir(directory);
94
+ await Promise.all(files.map(async (file) => {
95
+ const path = join(directory, file);
96
+ try {
97
+ if ((await stat(path)).mtimeMs < cutoff)
98
+ await unlink(path);
99
+ }
100
+ catch (error) {
101
+ if (error.code !== "ENOENT")
102
+ throw error;
103
+ }
104
+ }));
105
+ }
106
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,131 @@
1
+ import { createHash } from "node:crypto";
2
+ import { accountsPath, addAccount, APP_NAME, cachePath, loadConfiguredAccounts, loadAccounts, removeAccount, } from "./config.js";
3
+ import { probeQuota, quotaSummary } from "./pool.js";
4
+ const HELP = `Usage: ${APP_NAME} [command]
5
+
6
+ Commands:
7
+ serve Run the MCP server (default)
8
+ status Fetch current quota status for every account
9
+ accounts list List configured accounts and fingerprints
10
+ accounts add [name] Add an API key using a hidden prompt or stdin
11
+ accounts remove <name> Remove an account from the config file
12
+ config Show effective paths and runtime settings
13
+ help Show this help`;
14
+ export async function runCli(args) {
15
+ const [command, action, name] = args;
16
+ switch (command) {
17
+ case undefined:
18
+ case "serve":
19
+ return false;
20
+ case "help":
21
+ case "--help":
22
+ case "-h":
23
+ console.log(HELP);
24
+ return true;
25
+ case "status":
26
+ await showStatus();
27
+ return true;
28
+ case "config":
29
+ showConfig();
30
+ return true;
31
+ case "accounts":
32
+ if (action === "list")
33
+ await listAccounts();
34
+ else if (action === "add")
35
+ await configureAccount(name);
36
+ else if (action === "remove" && name) {
37
+ await removeAccount(name);
38
+ console.log(`Removed ${name}`);
39
+ }
40
+ else {
41
+ throw new Error("Use accounts list, accounts add [name], or accounts remove <name>");
42
+ }
43
+ return true;
44
+ default:
45
+ throw new Error(`Unknown command ${command}\n\n${HELP}`);
46
+ }
47
+ }
48
+ async function showStatus() {
49
+ const accounts = await loadAccounts();
50
+ if (accounts.length === 0)
51
+ throw new Error("No accounts configured");
52
+ console.error("Each status check consumes one Context7 API request per account.");
53
+ const statuses = await Promise.all(accounts.map(async ({ name, apiKey }) => {
54
+ try {
55
+ return { name, status: quotaSummary(await probeQuota(apiKey)) };
56
+ }
57
+ catch (error) {
58
+ return { name, status: `ERROR: ${error instanceof Error ? error.message : String(error)}` };
59
+ }
60
+ }));
61
+ for (const { name, status } of statuses)
62
+ console.log(`${name}\t${status}`);
63
+ }
64
+ async function listAccounts() {
65
+ const accounts = await loadAccounts();
66
+ if (accounts.length === 0) {
67
+ console.log("No accounts configured");
68
+ return;
69
+ }
70
+ for (const { name, apiKey, source } of accounts) {
71
+ const fingerprint = createHash("sha256").update(apiKey).digest("hex").slice(0, 12);
72
+ console.log(`${name}\t${source}\tsha256:${fingerprint}`);
73
+ }
74
+ }
75
+ async function configureAccount(requestedName) {
76
+ const configured = await loadConfiguredAccounts();
77
+ const name = requestedName ?? `account-${configured.length + 1}`;
78
+ const apiKey = (await readSecret("Context7 API key: ")).trim();
79
+ if (!apiKey)
80
+ throw new Error("API key cannot be empty");
81
+ await addAccount(name, apiKey);
82
+ console.log(`Added ${name} to ${accountsPath()}`);
83
+ }
84
+ function showConfig() {
85
+ const ttl = process.env.CONTEXT7_CACHE_TTL_DAYS || "30";
86
+ console.log(`accounts\t${accountsPath()}`);
87
+ console.log(`cache\t${cachePath()}`);
88
+ console.log(`cache TTL\t${ttl} days`);
89
+ console.log(`project\t${process.env.CONTEXT7_PROJECT_ID ?? process.cwd()}`);
90
+ console.log(`upstream\t${process.env.CONTEXT7_MCP_URL ?? "https://mcp.context7.com/mcp"}`);
91
+ }
92
+ async function readSecret(prompt) {
93
+ if (!process.stdin.isTTY) {
94
+ let value = "";
95
+ for await (const chunk of process.stdin)
96
+ value += chunk;
97
+ return value;
98
+ }
99
+ return new Promise((resolve, reject) => {
100
+ let value = "";
101
+ const stdin = process.stdin;
102
+ const cleanup = () => {
103
+ stdin.off("data", onData);
104
+ stdin.setRawMode(false);
105
+ stdin.pause();
106
+ process.stderr.write("\n");
107
+ };
108
+ const onData = (chunk) => {
109
+ for (const byte of chunk) {
110
+ if (byte === 3) {
111
+ cleanup();
112
+ reject(new Error("Cancelled"));
113
+ return;
114
+ }
115
+ if (byte === 10 || byte === 13) {
116
+ cleanup();
117
+ resolve(value);
118
+ return;
119
+ }
120
+ if (byte === 8 || byte === 127)
121
+ value = value.slice(0, -1);
122
+ else if (byte >= 32 && byte <= 126)
123
+ value += String.fromCharCode(byte);
124
+ }
125
+ };
126
+ process.stderr.write(prompt);
127
+ stdin.setRawMode(true);
128
+ stdin.resume();
129
+ stdin.on("data", onData);
130
+ });
131
+ }
package/dist/config.js ADDED
@@ -0,0 +1,113 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { chmod, mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join } from "node:path";
5
+ export const APP_NAME = "context7-account-broker";
6
+ const ACCOUNT_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
7
+ export function accountsPath(env = process.env) {
8
+ return (env.CONTEXT7_BROKER_CONFIG ??
9
+ join(env.XDG_CONFIG_HOME ?? join(homedir(), ".config"), APP_NAME, "accounts.json"));
10
+ }
11
+ export function cachePath(env = process.env) {
12
+ return (env.CONTEXT7_CACHE_DIR ??
13
+ join(env.XDG_CACHE_HOME ?? join(homedir(), ".cache"), APP_NAME));
14
+ }
15
+ export async function loadConfiguredAccounts(env = process.env) {
16
+ return (await readAccountsFile(env)).accounts;
17
+ }
18
+ export async function loadAccounts(env = process.env) {
19
+ const configured = await loadConfiguredAccounts(env);
20
+ const credentials = configured.map((account) => ({
21
+ ...account,
22
+ source: "config",
23
+ }));
24
+ if (configured.length > 0 && env.CONTEXT7_BROKER_INCLUDE_ENV !== "1") {
25
+ return credentials;
26
+ }
27
+ const knownKeys = new Set(configured.map(({ apiKey }) => apiKey));
28
+ const knownNames = new Set(configured.map(({ name }) => name));
29
+ const environmentKeys = [env.CONTEXT7_API_KEYS, env.CONTEXT7_API_KEY]
30
+ .flatMap((value) => value?.split(/[\s,]+/) ?? [])
31
+ .filter(Boolean);
32
+ let environmentIndex = 1;
33
+ for (const apiKey of new Set(environmentKeys)) {
34
+ if (knownKeys.has(apiKey))
35
+ continue;
36
+ while (knownNames.has(`env-${environmentIndex}`))
37
+ environmentIndex += 1;
38
+ const name = `env-${environmentIndex++}`;
39
+ credentials.push({ name, apiKey, source: "environment" });
40
+ knownNames.add(name);
41
+ }
42
+ return credentials;
43
+ }
44
+ export async function addAccount(name, apiKey, env = process.env) {
45
+ validateName(name);
46
+ if (!apiKey.startsWith("ctx7sk")) {
47
+ throw new Error("Context7 API keys must start with ctx7sk");
48
+ }
49
+ const file = await readAccountsFile(env);
50
+ if (file.accounts.some((account) => account.name === name)) {
51
+ throw new Error(`Account ${name} already exists`);
52
+ }
53
+ if (file.accounts.some((account) => account.apiKey === apiKey)) {
54
+ throw new Error("That API key is already configured");
55
+ }
56
+ file.accounts.push({ name, apiKey });
57
+ await writeAccountsFile(file, env);
58
+ }
59
+ export async function removeAccount(name, env = process.env) {
60
+ const file = await readAccountsFile(env);
61
+ const accounts = file.accounts.filter((account) => account.name !== name);
62
+ if (accounts.length === file.accounts.length) {
63
+ throw new Error(`Configured account ${name} does not exist`);
64
+ }
65
+ await writeAccountsFile({ ...file, accounts }, env);
66
+ }
67
+ function validateName(name) {
68
+ if (!ACCOUNT_NAME.test(name)) {
69
+ throw new Error("Account names must use 1-64 letters, numbers, dots, underscores, or hyphens");
70
+ }
71
+ }
72
+ async function readAccountsFile(env) {
73
+ const path = accountsPath(env);
74
+ let value;
75
+ try {
76
+ value = JSON.parse(await readFile(path, "utf8"));
77
+ }
78
+ catch (error) {
79
+ if (error.code === "ENOENT")
80
+ return { version: 1, accounts: [] };
81
+ throw new Error(`Cannot read ${path}: ${String(error)}`);
82
+ }
83
+ if (!isAccountsFile(value))
84
+ throw new Error(`Invalid account configuration in ${path}`);
85
+ return value;
86
+ }
87
+ function isAccountsFile(value) {
88
+ if (!value || typeof value !== "object")
89
+ return false;
90
+ const file = value;
91
+ return (file.version === 1 &&
92
+ Array.isArray(file.accounts) &&
93
+ file.accounts.every((account) => account &&
94
+ typeof account.name === "string" &&
95
+ ACCOUNT_NAME.test(account.name) &&
96
+ typeof account.apiKey === "string" &&
97
+ account.apiKey.startsWith("ctx7sk")) &&
98
+ new Set(file.accounts.map(({ name }) => name)).size === file.accounts.length &&
99
+ new Set(file.accounts.map(({ apiKey }) => apiKey)).size === file.accounts.length);
100
+ }
101
+ async function writeAccountsFile(file, env) {
102
+ const path = accountsPath(env);
103
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
104
+ const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
105
+ try {
106
+ await writeFile(temporary, `${JSON.stringify(file, null, 2)}\n`, { mode: 0o600 });
107
+ await rename(temporary, path);
108
+ await chmod(path, 0o600);
109
+ }
110
+ finally {
111
+ await unlink(temporary).catch(() => undefined);
112
+ }
113
+ }
package/dist/index.js ADDED
@@ -0,0 +1,105 @@
1
+ #!/usr/bin/env node
2
+ import { createHash } from "node:crypto";
3
+ import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
4
+ import { McpServer, } from "@modelcontextprotocol/server";
5
+ import { serveStdio } from "@modelcontextprotocol/server/stdio";
6
+ import { ResultCache } from "./cache.js";
7
+ import { runCli } from "./cli.js";
8
+ import { APP_NAME, cachePath, loadAccounts } from "./config.js";
9
+ import { AccountPool, probeQuota, quotaSummary, } from "./pool.js";
10
+ const VERSION = "0.1.0";
11
+ function message(error) {
12
+ return error instanceof Error ? error.message : String(error);
13
+ }
14
+ function createServer(pool) {
15
+ const server = new McpServer({
16
+ name: "Context7",
17
+ version: VERSION,
18
+ websiteUrl: "https://context7.com",
19
+ description: "A multi-account forwarding proxy for Context7 documentation tools.",
20
+ }, {
21
+ instructions: "Use this server exactly like Context7. Account selection and failover are automatic.",
22
+ });
23
+ // Low-level handlers preserve the upstream schemas and results without translation.
24
+ server.server.registerCapabilities({ tools: {} });
25
+ server.server.setRequestHandler("tools/list", async () => ({ tools: [...pool.tools] }));
26
+ server.server.setRequestHandler("tools/call", async ({ params }) => pool.callTool(params.name, params.arguments));
27
+ return server;
28
+ }
29
+ async function main() {
30
+ if (await runCli(process.argv.slice(2)))
31
+ return;
32
+ const credentials = await loadAccounts();
33
+ if (credentials.length === 0) {
34
+ throw new Error(`No accounts configured. Run ${APP_NAME} accounts add or set CONTEXT7_API_KEYS`);
35
+ }
36
+ const endpoint = new URL(process.env.CONTEXT7_MCP_URL ?? "https://mcp.context7.com/mcp");
37
+ if (endpoint.protocol !== "http:" && endpoint.protocol !== "https:") {
38
+ throw new Error("CONTEXT7_MCP_URL must use HTTP or HTTPS");
39
+ }
40
+ const cooldownMs = Number(process.env.CONTEXT7_ACCOUNT_COOLDOWN_MS || 30_000);
41
+ if (!Number.isInteger(cooldownMs) || cooldownMs < 0) {
42
+ throw new Error("CONTEXT7_ACCOUNT_COOLDOWN_MS must be a non-negative integer");
43
+ }
44
+ const cacheTtlDays = Number(process.env.CONTEXT7_CACHE_TTL_DAYS || 30);
45
+ if (!Number.isFinite(cacheTtlDays) || cacheTtlDays <= 0) {
46
+ throw new Error("CONTEXT7_CACHE_TTL_DAYS must be a positive number");
47
+ }
48
+ const cache = await ResultCache.open(cachePath(), cacheTtlDays * 86_400_000);
49
+ const projectScope = process.env.CONTEXT7_PROJECT_ID ?? process.cwd();
50
+ const connected = await Promise.all(credentials.map(async ({ name: id, apiKey }) => {
51
+ const client = new Client({ name: APP_NAME, version: VERSION });
52
+ const transport = new StreamableHTTPClientTransport(endpoint, {
53
+ authProvider: { token: async () => apiKey },
54
+ onInsufficientScope: "throw",
55
+ requestInit: { headers: { "User-Agent": `${APP_NAME}/${VERSION}` } },
56
+ });
57
+ try {
58
+ const quota = await probeQuota(apiKey);
59
+ await client.connect(transport);
60
+ const { tools } = await client.listTools();
61
+ if (tools.length === 0)
62
+ throw new Error("upstream advertised no tools");
63
+ console.error(`[${APP_NAME}] ${id} quota: ${quotaSummary(quota)}`);
64
+ return {
65
+ id,
66
+ accountKey: createHash("sha256").update(apiKey).digest("hex"),
67
+ client,
68
+ tools,
69
+ quota,
70
+ refreshQuota: () => probeQuota(apiKey),
71
+ };
72
+ }
73
+ catch (error) {
74
+ console.error(`[${APP_NAME}] Skipping ${id}: ${message(error)}`);
75
+ await client.close().catch((closeError) => console.error(`[${APP_NAME}] Failed to close ${id}: ${message(closeError)}`));
76
+ }
77
+ }));
78
+ const accounts = connected.filter((account) => account !== undefined);
79
+ let pool;
80
+ try {
81
+ pool = new AccountPool(accounts, cooldownMs, cache, projectScope);
82
+ }
83
+ catch (error) {
84
+ await Promise.allSettled(accounts.map(({ client }) => client.close()));
85
+ throw error;
86
+ }
87
+ console.error(`[${APP_NAME}] Connected ${accounts.length} account(s); forwarding ${pool.tools
88
+ .map(({ name }) => name)
89
+ .join(", ")}`);
90
+ const handle = serveStdio(() => createServer(pool), {
91
+ onerror: (error) => console.error(`[${APP_NAME}] MCP error: ${message(error)}`),
92
+ });
93
+ let closing;
94
+ const shutdown = () => (closing ??= Promise.all([handle.close(), pool.close()]).then(() => undefined));
95
+ const requestShutdown = () => {
96
+ void shutdown().catch((error) => console.error(`[${APP_NAME}] Shutdown failed: ${message(error)}`));
97
+ };
98
+ process.once("SIGINT", requestShutdown);
99
+ process.once("SIGTERM", requestShutdown);
100
+ process.stdin.once("end", requestShutdown);
101
+ }
102
+ void main().catch((error) => {
103
+ console.error(`[${APP_NAME}] Fatal error: ${message(error)}`);
104
+ process.exitCode = 1;
105
+ });
package/dist/pool.js ADDED
@@ -0,0 +1,251 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+ import { InsufficientScopeError, SdkError, SdkErrorCode, SdkHttpError, UnauthorizedError, } from "@modelcontextprotocol/client";
3
+ import { ProtocolError, ProtocolErrorCode, } from "@modelcontextprotocol/server";
4
+ const RETRYABLE_HTTP_STATUSES = new Set([401, 403, 408, 425, 429, 500, 502, 503, 504]);
5
+ const RETRYABLE_SDK_ERRORS = new Set([
6
+ SdkErrorCode.NotConnected,
7
+ SdkErrorCode.RequestTimeout,
8
+ SdkErrorCode.ConnectionClosed,
9
+ SdkErrorCode.SendFailed,
10
+ ]);
11
+ const RETRYABLE_NETWORK_ERRORS = new Set([
12
+ "EAI_AGAIN",
13
+ "ECONNREFUSED",
14
+ "ECONNRESET",
15
+ "EHOSTUNREACH",
16
+ "ENETUNREACH",
17
+ "ENOTFOUND",
18
+ "ETIMEDOUT",
19
+ "UND_ERR_CONNECT_TIMEOUT",
20
+ "UND_ERR_HEADERS_TIMEOUT",
21
+ "UND_ERR_SOCKET",
22
+ ]);
23
+ const QUOTA_RESULT = /^(?:monthly quota reached|rate limited or quota exceeded)/i;
24
+ const RETRYABLE_RESULT = /^(?:monthly quota reached|rate limited or quota exceeded|invalid api key|authentication required|request failed with status (?:40[1238]|425|429|5\d\d)\b|error (?:searching libraries:|fetching library context\.))/i;
25
+ function message(error) {
26
+ return error instanceof Error ? error.message : String(error);
27
+ }
28
+ function resultText(result) {
29
+ return result.content
30
+ .flatMap((block) => (block.type === "text" ? [block.text] : []))
31
+ .join("\n");
32
+ }
33
+ function isRetryableError(error) {
34
+ if (error instanceof UnauthorizedError || error instanceof InsufficientScopeError)
35
+ return true;
36
+ if (error instanceof SdkHttpError)
37
+ return RETRYABLE_HTTP_STATUSES.has(error.status);
38
+ if (error instanceof SdkError)
39
+ return RETRYABLE_SDK_ERRORS.has(error.code);
40
+ const cause = error instanceof Error ? error.cause : undefined;
41
+ const code = cause && typeof cause === "object" && "code" in cause ? String(cause.code) : undefined;
42
+ return code !== undefined && RETRYABLE_NETWORK_ERRORS.has(code);
43
+ }
44
+ function brokerError(text) {
45
+ return {
46
+ content: [{ type: "text", text: `[context7-account-broker] ${text}` }],
47
+ isError: true,
48
+ };
49
+ }
50
+ function nextUtcDay(now = new Date()) {
51
+ return Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() + 1);
52
+ }
53
+ function nextQuotaRefresh(quota) {
54
+ return quota.blocked ? Math.min(quota.resetAt, nextUtcDay()) : quota.resetAt;
55
+ }
56
+ function affinitySubject(tool, args) {
57
+ const value = tool === "query-docs"
58
+ ? args?.libraryId
59
+ : tool === "resolve-library-id"
60
+ ? args?.libraryName
61
+ : undefined;
62
+ return typeof value === "string" ? `library:${value.toLowerCase()}` : `tool:${tool}`;
63
+ }
64
+ function resolvedLibraries(result) {
65
+ return [...resultText(result).matchAll(/Context7-compatible library ID:\s*(\/\S+)/g)].map(([, libraryId]) => `library:${libraryId?.toLowerCase()}`);
66
+ }
67
+ export async function probeQuota(apiKey) {
68
+ const url = new URL("https://context7.com/api/v2/libs/search");
69
+ url.searchParams.set("libraryName", "Context7");
70
+ url.searchParams.set("query", "quota status check");
71
+ const response = await fetch(url, { headers: { Authorization: `Bearer ${apiKey}` } });
72
+ if (response.status !== 200 && response.status !== 429) {
73
+ const body = await response.text();
74
+ throw new Error(`quota check returned HTTP ${response.status}${body ? `: ${body}` : ""}`);
75
+ }
76
+ const header = (name) => {
77
+ const value = response.headers.get(name);
78
+ if (value === null)
79
+ throw new Error(`quota check omitted ${name}`);
80
+ return Number(value);
81
+ };
82
+ const limit = header("RateLimit-Limit");
83
+ const remaining = header("RateLimit-Remaining");
84
+ const resetAt = header("RateLimit-Reset") * 1000;
85
+ await response.body?.cancel();
86
+ if (![limit, remaining, resetAt].every(Number.isInteger) ||
87
+ limit <= 0 ||
88
+ remaining > limit ||
89
+ resetAt <= 0) {
90
+ throw new Error("quota check returned invalid rate-limit headers");
91
+ }
92
+ return {
93
+ limit,
94
+ remaining,
95
+ resetAt,
96
+ updatedAt: Date.now(),
97
+ blocked: response.status === 429,
98
+ };
99
+ }
100
+ export function quotaSummary({ limit, remaining, resetAt, blocked }) {
101
+ const used = limit - remaining;
102
+ const percentage = Math.round((used / limit) * 100);
103
+ return `${used}/${limit} used (${percentage}%)${blocked ? ", blocked" : ""}; resets ${new Date(resetAt).toISOString()}`;
104
+ }
105
+ export class AccountPool {
106
+ cooldownMs;
107
+ cache;
108
+ scope;
109
+ tools;
110
+ accounts;
111
+ toolNames;
112
+ inFlight = new Map();
113
+ nextAccount = 0;
114
+ constructor(accounts, cooldownMs, cache, scope) {
115
+ this.cooldownMs = cooldownMs;
116
+ this.cache = cache;
117
+ this.scope = scope;
118
+ const [first, ...rest] = accounts;
119
+ if (!first)
120
+ throw new Error("No configured Context7 account could be connected");
121
+ for (const account of rest) {
122
+ if (!isDeepStrictEqual(account.tools, first.tools)) {
123
+ throw new Error(`${account.id} advertised tools that differ from ${first.id}`);
124
+ }
125
+ }
126
+ this.tools = first.tools;
127
+ this.toolNames = new Set(first.tools.map(({ name }) => name));
128
+ this.accounts = accounts.map((account, index) => ({
129
+ ...account,
130
+ index,
131
+ cooldownUntil: 0,
132
+ quotaRefreshAt: nextQuotaRefresh(account.quota),
133
+ }));
134
+ }
135
+ refreshQuota(account) {
136
+ if (!account.refreshing) {
137
+ account.refreshing = account
138
+ .refreshQuota()
139
+ .then((quota) => {
140
+ account.quota = quota;
141
+ account.quotaRefreshAt = nextQuotaRefresh(quota);
142
+ account.cooldownUntil = 0;
143
+ console.error(`[context7-account-broker] ${account.id} quota: ${quotaSummary(quota)}`);
144
+ })
145
+ .catch((error) => {
146
+ account.quotaRefreshAt = Date.now() + this.cooldownMs;
147
+ console.error(`[context7-account-broker] Failed to refresh ${account.id} quota: ${message(error)}`);
148
+ })
149
+ .finally(() => {
150
+ account.refreshing = undefined;
151
+ });
152
+ }
153
+ return account.refreshing;
154
+ }
155
+ callTool(name, args) {
156
+ const requestKey = this.cache.requestKey(this.scope, name, args);
157
+ const running = this.inFlight.get(requestKey);
158
+ if (running)
159
+ return running;
160
+ const request = this.callToolOnce(name, args, requestKey).finally(() => {
161
+ this.inFlight.delete(requestKey);
162
+ });
163
+ this.inFlight.set(requestKey, request);
164
+ return request;
165
+ }
166
+ async callToolOnce(name, args, requestKey) {
167
+ if (!this.toolNames.has(name)) {
168
+ throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Tool ${name} not found`);
169
+ }
170
+ const subject = affinitySubject(name, args);
171
+ const assignedKey = await this.cache.getAffinity(this.scope, subject);
172
+ const assigned = this.accounts.find(({ accountKey }) => accountKey === assignedKey);
173
+ const cacheOrder = assigned
174
+ ? [assigned, ...this.accounts.filter((account) => account !== assigned)]
175
+ : this.accounts;
176
+ for (const account of cacheOrder) {
177
+ const cached = await this.cache.getResult(requestKey, account.accountKey);
178
+ if (cached) {
179
+ console.error(`[context7-account-broker] Cache hit for ${name}`);
180
+ if (!assigned)
181
+ await this.cache.setAffinity(this.scope, subject, account.accountKey);
182
+ return cached;
183
+ }
184
+ }
185
+ const now = Date.now();
186
+ await Promise.all(this.accounts
187
+ .filter(({ quotaRefreshAt }) => quotaRefreshAt <= now)
188
+ .map((account) => this.refreshQuota(account)));
189
+ const distance = (index) => (index - this.nextAccount + this.accounts.length) % this.accounts.length;
190
+ const candidates = this.accounts
191
+ .filter((account) => !account.quota.blocked && account.cooldownUntil <= Date.now())
192
+ .sort((a, b) => (a === assigned ? -1 : b === assigned ? 1 : 0) ||
193
+ (a.quota.limit - a.quota.remaining) / a.quota.limit -
194
+ (b.quota.limit - b.quota.remaining) / b.quota.limit ||
195
+ distance(a.index) - distance(b.index));
196
+ let lastFailure;
197
+ for (const account of candidates) {
198
+ this.nextAccount = (account.index + 1) % this.accounts.length;
199
+ account.quota.remaining -= 1;
200
+ account.quota.updatedAt = Date.now();
201
+ try {
202
+ const result = await account.client.callTool({ name, arguments: args });
203
+ const text = resultText(result).trim();
204
+ if (!RETRYABLE_RESULT.test(text)) {
205
+ if (!result.isError) {
206
+ const affinities = [subject, ...(name === "resolve-library-id" ? resolvedLibraries(result) : [])];
207
+ await Promise.all([
208
+ this.cache.setResult(requestKey, account.accountKey, result),
209
+ ...affinities.map((key) => this.cache.setAffinity(this.scope, key, account.accountKey)),
210
+ ]).catch((error) => console.warn(`[context7-account-broker] Failed to update cache: ${message(error)}`));
211
+ }
212
+ return result;
213
+ }
214
+ lastFailure = text || "retryable upstream failure";
215
+ if (QUOTA_RESULT.test(text)) {
216
+ account.quota.blocked = true;
217
+ account.quota.remaining = 0;
218
+ account.quotaRefreshAt = nextQuotaRefresh(account.quota);
219
+ }
220
+ else {
221
+ account.cooldownUntil = Date.now() + this.cooldownMs;
222
+ }
223
+ }
224
+ catch (error) {
225
+ if (!isRetryableError(error)) {
226
+ console.error(`[context7-account-broker] ${account.id} failed: ${message(error)}`);
227
+ throw error;
228
+ }
229
+ lastFailure = message(error);
230
+ account.cooldownUntil = Date.now() + this.cooldownMs;
231
+ }
232
+ console.warn(`[context7-account-broker] ${account.id} unavailable: ${lastFailure}`);
233
+ }
234
+ if (lastFailure !== undefined) {
235
+ console.error(`[context7-account-broker] All accounts failed for ${name}: ${lastFailure}`);
236
+ return brokerError(`All configured Context7 accounts failed for ${name}.`);
237
+ }
238
+ const retryAt = Math.min(...this.accounts.map((account) => account.quota.blocked ? account.quotaRefreshAt : account.cooldownUntil));
239
+ const retryDate = new Date(retryAt).toISOString();
240
+ console.warn(`[context7-account-broker] All accounts unavailable until ${retryDate}`);
241
+ return brokerError(`All configured Context7 accounts are unavailable. Retry after ${retryDate}.`);
242
+ }
243
+ async close() {
244
+ const results = await Promise.allSettled(this.accounts.map(({ client }) => client.close()));
245
+ results.forEach((result, index) => {
246
+ if (result.status === "rejected") {
247
+ console.error(`[context7-account-broker] Failed to close ${this.accounts[index]?.id}: ${message(result.reason)}`);
248
+ }
249
+ });
250
+ }
251
+ }
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@mirsella/context7-account-broker",
3
+ "version": "0.1.0",
4
+ "description": "Quota-aware Context7 MCP broker with multi-account routing, caching, affinity, and failover.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "packageManager": "pnpm@10.14.0",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/mirsella/context7-account-broker.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/mirsella/context7-account-broker/issues"
14
+ },
15
+ "homepage": "https://github.com/mirsella/context7-account-broker#readme",
16
+ "engines": {
17
+ "node": ">=20"
18
+ },
19
+ "bin": {
20
+ "context7-account-broker": "dist/index.js"
21
+ },
22
+ "files": [
23
+ "dist",
24
+ "README.md",
25
+ "LICENSE"
26
+ ],
27
+ "scripts": {
28
+ "build": "tsc",
29
+ "start": "node dist/index.js",
30
+ "test": "vitest run",
31
+ "typecheck": "tsc --noEmit",
32
+ "prepare": "tsc"
33
+ },
34
+ "publishConfig": {
35
+ "access": "public"
36
+ },
37
+ "dependencies": {
38
+ "@modelcontextprotocol/client": "2.0.0",
39
+ "@modelcontextprotocol/server": "2.0.0"
40
+ },
41
+ "devDependencies": {
42
+ "@types/node": "^25.0.3",
43
+ "typescript": "^5.8.2",
44
+ "vitest": "^4.1.9"
45
+ }
46
+ }