@mirsella/context7-account-broker 0.1.0 → 0.2.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/README.md CHANGED
@@ -1,216 +1,65 @@
1
- # Context7 Account Broker
1
+ # context7-account-broker
2
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)
3
+ An OpenCode plugin that runs one local Context7 MCP broker across projects and shares quota, caching, affinity, and in-flight requests across configured API keys.
6
4
 
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.
5
+ ## Setup
10
6
 
11
- OpenCode sees the standard Context7 tools:
7
+ Add at least one Context7 account:
12
8
 
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
9
+ ```sh
10
+ bunx @mirsella/context7-account-broker accounts add personal
39
11
  ```
40
12
 
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
- ```
13
+ The command reads the API key from a hidden terminal prompt and stores it in a private `accounts.json` file.
47
14
 
48
- ### 2. Configure OpenCode
15
+ Then add the plugin to `opencode.json`:
49
16
 
50
- Add the server to `~/.config/opencode/opencode.jsonc`:
51
-
52
- ```jsonc
17
+ ```json
53
18
  {
54
- "mcp": {
55
- "context7": {
56
- "type": "local",
57
- "command": ["npx", "-y", "@mirsella/context7-account-broker"],
58
- "timeout": 30000,
59
- "enabled": true
60
- }
61
- }
19
+ "plugin": ["@mirsella/context7-account-broker"]
62
20
  }
63
21
  ```
64
22
 
65
- Restart OpenCode, then check the connection:
23
+ That is the complete OpenCode configuration. Do not add an `mcp.context7-broker` entry: the plugin creates it and refuses to replace an existing entry.
66
24
 
67
- ```bash
68
- opencode mcp list
69
- ```
25
+ ## Lifecycle
70
26
 
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
- ```
27
+ When OpenCode loads the plugin, the packaged Linux x64 binary runs `start`. It creates a private server token if needed, reuses an authenticated healthy broker on `127.0.0.1:14197`, or launches the shared broker and waits briefly for readiness. The plugin reads the token into OpenCode's in-memory MCP configuration; it never writes the token to `opencode.json` or passes it in process arguments.
104
28
 
105
- ## Account selection
29
+ The broker stays available across project and session lifetimes. Its containing process manager may stop it with OpenCode; a later plugin launch reuses it when healthy or starts a replacement when it is absent. There is no supervisor, heartbeat, separate systemd unit, PATH installation, manual token, or last-client shutdown.
106
30
 
107
- At startup, the broker probes each key and reads Context7's authoritative
108
- `RateLimit-Limit`, `RateLimit-Remaining`, and `RateLimit-Reset` headers.
31
+ Startup makes no Context7 requests. Context7 is contacted only for tool calls and the explicit `status` command.
109
32
 
110
- For a library without an existing assignment, it chooses the available account
111
- with the lowest proportional usage:
33
+ ## Commands
112
34
 
113
35
  ```text
114
- used / limit = (limit - remaining) / limit
36
+ context7-account-broker start
37
+ context7-account-broker serve
38
+ context7-account-broker accounts list
39
+ context7-account-broker accounts add NAME
40
+ context7-account-broker accounts remove NAME
41
+ context7-account-broker status
42
+ context7-account-broker config
115
43
  ```
116
44
 
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.
45
+ Use `bunx @mirsella/context7-account-broker ...` when the package is not otherwise installed.
120
46
 
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.
47
+ ## Architecture
124
48
 
125
- ## Cache
49
+ The plugin contains a static `x86_64-unknown-linux-musl` binary. One current-thread Tokio process exposes authenticated Streamable HTTP MCP on loopback. It forwards requests directly to the official Context7 REST API with bounded concurrency four.
126
50
 
127
- Successful tool results are cached by:
51
+ The broker provides the canonical `resolve-library-id` and `query-docs` tools. It routes toward account affinity and lower quota use, rotates unknown quota fairly, fails over account-specific `401`, `403`, and `429` responses, and caps shared endpoint failures at two attempts. Successful results use an account-partitioned disk cache. Identical typed requests share one cancellation-safe in-flight producer.
128
52
 
129
- - project scope
130
- - tool name
131
- - canonicalized arguments
132
- - API-key hash
53
+ Default private state:
133
54
 
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
- ```
55
+ - Accounts: `$XDG_CONFIG_HOME/context7-account-broker/accounts.json`
56
+ - Server token: `$XDG_CONFIG_HOME/context7-account-broker/server-token`
57
+ - Cache and launch log: `$XDG_CACHE_HOME/context7-account-broker/`
207
58
 
208
- ## Responsible use
59
+ Optional environment settings are `CONTEXT7_BROKER_CONFIG`, `CONTEXT7_API_KEY`, `CONTEXT7_API_KEYS`, `CONTEXT7_BROKER_INCLUDE_ENV`, `CONTEXT7_BROKER_TOKEN_FILE`, `CONTEXT7_CACHE_DIR`, `CONTEXT7_CACHE_TTL_DAYS`, `CONTEXT7_ACCOUNT_COOLDOWN_MS`, and `CONTEXT7_BROKER_PORT`.
209
60
 
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.
61
+ The package supports Linux x64 only.
213
62
 
214
63
  ## License
215
64
 
216
- [MIT](LICENSE)
65
+ MIT
package/package.json CHANGED
@@ -1,46 +1,53 @@
1
1
  {
2
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",
3
+ "version": "0.2.0",
4
+ "description": "Seamless multi-account Context7 plugin for OpenCode",
6
5
  "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"
6
+ "exports": {
7
+ "./server": "./plugin/context7.ts"
18
8
  },
19
9
  "bin": {
20
- "context7-account-broker": "dist/index.js"
10
+ "context7-account-broker": "vendor/context7-account-broker"
21
11
  },
22
12
  "files": [
23
- "dist",
13
+ "plugin/",
14
+ "vendor/",
24
15
  "README.md",
25
16
  "LICENSE"
26
17
  ],
27
18
  "scripts": {
28
- "build": "tsc",
29
- "start": "node dist/index.js",
30
- "test": "vitest run",
31
- "typecheck": "tsc --noEmit",
32
- "prepare": "tsc"
19
+ "build:native": "cargo build --locked --release --target x86_64-unknown-linux-musl",
20
+ "stage:native": "node scripts/stage-native.mjs",
21
+ "test": "cargo test --locked && bun test tests/plugin.test.ts",
22
+ "prepack": "pnpm build:native && pnpm stage:native"
33
23
  },
34
- "publishConfig": {
35
- "access": "public"
24
+ "keywords": [
25
+ "opencode",
26
+ "context7",
27
+ "mcp"
28
+ ],
29
+ "homepage": "https://github.com/mirsella/context7-account-broker#readme",
30
+ "bugs": "https://github.com/mirsella/context7-account-broker/issues",
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "git+https://github.com/mirsella/context7-account-broker.git"
36
34
  },
37
- "dependencies": {
38
- "@modelcontextprotocol/client": "2.0.0",
39
- "@modelcontextprotocol/server": "2.0.0"
35
+ "license": "MIT",
36
+ "author": "mirsella",
37
+ "os": [
38
+ "linux"
39
+ ],
40
+ "cpu": [
41
+ "x64"
42
+ ],
43
+ "engines": {
44
+ "opencode": ">=1.18.0"
40
45
  },
46
+ "packageManager": "pnpm@10.14.0",
41
47
  "devDependencies": {
42
- "@types/node": "^25.0.3",
43
- "typescript": "^5.8.2",
44
- "vitest": "^4.1.9"
48
+ "@opencode-ai/plugin": "1.18.11"
49
+ },
50
+ "publishConfig": {
51
+ "access": "public"
45
52
  }
46
53
  }
@@ -0,0 +1,79 @@
1
+ import type { Plugin, PluginModule } from "@opencode-ai/plugin";
2
+ import { readFile } from "node:fs/promises";
3
+ import { fileURLToPath } from "node:url";
4
+
5
+ const BINARY = fileURLToPath(new URL("../vendor/context7-account-broker", import.meta.url));
6
+ const MCP_NAME = "context7-broker";
7
+
8
+ type NativeLaunch = {
9
+ url: string;
10
+ tokenFile: string;
11
+ };
12
+
13
+ export function parseNativeLaunch(stdout: string): NativeLaunch {
14
+ let value: unknown;
15
+ try {
16
+ value = JSON.parse(stdout);
17
+ } catch {
18
+ throw new Error("context7-account-broker start returned invalid JSON");
19
+ }
20
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
21
+ throw new Error("context7-account-broker start returned an invalid launch object");
22
+ }
23
+ const launch = value as Record<string, unknown>;
24
+ if (Object.keys(launch).sort().join(",") !== "tokenFile,url") {
25
+ throw new Error("context7-account-broker start returned unexpected fields");
26
+ }
27
+ if (typeof launch.url !== "string" || typeof launch.tokenFile !== "string") {
28
+ throw new Error("context7-account-broker start returned invalid launch fields");
29
+ }
30
+ const url = new URL(launch.url);
31
+ if (
32
+ url.protocol !== "http:" ||
33
+ url.hostname !== "127.0.0.1" ||
34
+ !url.port ||
35
+ url.pathname !== "/mcp" ||
36
+ url.username ||
37
+ url.password ||
38
+ url.search ||
39
+ url.hash ||
40
+ !launch.tokenFile.startsWith("/")
41
+ ) {
42
+ throw new Error("context7-account-broker start returned an unsafe launch target");
43
+ }
44
+ return { url: launch.url, tokenFile: launch.tokenFile };
45
+ }
46
+
47
+ export const server: Plugin = async ({ $ }) => ({
48
+ config: async (config) => {
49
+ if (config.mcp?.[MCP_NAME] !== undefined) {
50
+ throw new Error(
51
+ `@mirsella/context7-account-broker cannot replace the existing mcp.${MCP_NAME} configuration`,
52
+ );
53
+ }
54
+ const result = await $`${[BINARY, "start"]}`.quiet().nothrow();
55
+ if (result.exitCode !== 0) {
56
+ const stderr = String(result.stderr).trim();
57
+ throw new Error(
58
+ `context7-account-broker start failed with exit code ${result.exitCode}${stderr ? `: ${stderr}` : ""}`,
59
+ );
60
+ }
61
+ const launch = parseNativeLaunch(String(result.stdout));
62
+ const token = (await readFile(launch.tokenFile, "utf8")).trim();
63
+ if (!/^[0-9a-f]{64}$/.test(token)) {
64
+ throw new Error("context7-account-broker server token is invalid");
65
+ }
66
+ config.mcp ??= {};
67
+ config.mcp[MCP_NAME] = {
68
+ type: "remote",
69
+ url: launch.url,
70
+ enabled: true,
71
+ timeout: 30_000,
72
+ headers: {
73
+ Authorization: `Bearer ${token}`,
74
+ },
75
+ };
76
+ },
77
+ });
78
+
79
+ export default { id: "@mirsella/context7-account-broker", server } satisfies PluginModule;
Binary file
package/dist/cache.js DELETED
@@ -1,106 +0,0 @@
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 DELETED
@@ -1,131 +0,0 @@
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 DELETED
@@ -1,113 +0,0 @@
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 DELETED
@@ -1,105 +0,0 @@
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 DELETED
@@ -1,251 +0,0 @@
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
- }