rivet-mcp 0.0.0-stage → 1.0.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,3 +1,66 @@
1
- # Temporary Holding Version
1
+ # rivet-mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ stdio-мост для подключения Claude Code (и любых stdio MCP-клиентов) к Rivet (`/mcp`, Streamable HTTP).
4
+
5
+ Мост обменивает GitLab PAT на короткоживущий MCP-токен (`POST /api/auth/gitlab/exchange`, TTL 15 минут),
6
+ передаёт его в `Authorization: Bearer` и обновляет автоматически при 401 (один retry после re-exchange).
7
+ PAT ходит только до exchange-эндпоинта rivet — он не попадает ни в аргументы процесса, ни в трафик MCP.
8
+ Rivet в ответе exchange возвращает GitLab-инстанс, где реально проверен PAT, — мост сверяет его с
9
+ ожидаемым `GITLAB_URL` и отказывается работать при расхождении. `http://` разрешён только для
10
+ localhost (dev-стенд), всё остальное — только `https://`.
11
+
12
+ ## Переменные окружения
13
+
14
+ | Переменная | Обязательна | Описание |
15
+ |---|---|---|
16
+ | `GITLAB_TOKEN` | да | GitLab PAT (scope `read_api`) для exchange |
17
+ | `GITLAB_URL` | да | GitLab-инстанс, где должен быть проверен PAT (сверяется с ответом exchange) |
18
+ | `RIVET_URL` | да | База rivet: `<RIVET_URL>/mcp/` и `<RIVET_URL>/api/auth/gitlab/exchange` |
19
+
20
+ ## Подключение к Claude Code
21
+
22
+ До публикации пакета — по пути сборки:
23
+
24
+ ```bash
25
+ cd npm/rivet-mcp && npm install && npm run build
26
+
27
+ claude mcp add rivet \
28
+ -e GITLAB_TOKEN=glpat-<ваш PAT> \
29
+ -e GITLAB_URL=https://gitlab.example.com \
30
+ -e RIVET_URL=https://rivet.example.com \
31
+ -- node "$PWD/dist/cli.js" --scope user
32
+ ```
33
+
34
+ После публикации:
35
+
36
+ ```bash
37
+ claude mcp add rivet \
38
+ -e GITLAB_TOKEN=glpat-<ваш PAT> \
39
+ -e GITLAB_URL=https://gitlab.example.com \
40
+ -e RIVET_URL=https://rivet.example.com \
41
+ -- npx -y rivet-mcp@1.0.0
42
+ ```
43
+
44
+ `GITLAB_TOKEN` можно взять из переменной окружения shell (`-e GITLAB_TOKEN` без значения
45
+ наследует её) — тогда PAT не попадает в `~/.claude.json`.
46
+
47
+ ## Проксируемые методы
48
+
49
+ `tools/list`, `tools/call`, `resources/list`, `resources/read` — capabilities rivet (инструменты и
50
+ `rivet://instructions/*`). Prompts/sampling/elicitation не объявляются.
51
+
52
+ ## Диагностика
53
+
54
+ Мост пишет в **stderr** (stdout зарезервирован MCP-протоколом):
55
+
56
+ ```
57
+ rivet-mcp-bridge: connected to https://rivet.example.com/mcp/ (gitlab: https://gitlab.example.com)
58
+ rivet-mcp-bridge: rivet token exchange failed: HTTP 401 {"detail":"Invalid GitLab PAT"}
59
+ rivet-mcp-bridge: rivet token exchange: GitLab instance mismatch (expected https://gitlab.example.com, got https://evil.example)
60
+ ```
61
+
62
+ ## Публикация
63
+
64
+ ```bash
65
+ npm publish --access public
66
+ ```
package/dist/auth.js ADDED
@@ -0,0 +1,63 @@
1
+ const REFRESH_MARGIN_MS = 30_000;
2
+ const DEFAULT_TTL_MS = 15 * 60_000;
3
+ /**
4
+ * Обмен GitLab PAT на короткоживущий MCP-токен (POST /api/auth/gitlab/exchange)
5
+ * с кешем, досрочным обновлением и single-flight для параллельных вызовов.
6
+ */
7
+ export class RivetTokenProvider {
8
+ exchangeUrl;
9
+ gitlabPat;
10
+ expectedGitlabUrl;
11
+ timeoutMs;
12
+ token;
13
+ expiresAt = 0;
14
+ pending;
15
+ constructor(exchangeUrl, gitlabPat,
16
+ /** Ожидаемый GitLab-инстанс; rivet возвращает его в ответе exchange для сверки. */
17
+ expectedGitlabUrl, timeoutMs = 10_000) {
18
+ this.exchangeUrl = exchangeUrl;
19
+ this.gitlabPat = gitlabPat;
20
+ this.expectedGitlabUrl = expectedGitlabUrl;
21
+ this.timeoutMs = timeoutMs;
22
+ }
23
+ async getToken() {
24
+ if (this.token && Date.now() < this.expiresAt - REFRESH_MARGIN_MS) {
25
+ return this.token;
26
+ }
27
+ if (!this.pending) {
28
+ this.pending = this.exchange().finally(() => {
29
+ this.pending = undefined;
30
+ });
31
+ }
32
+ return this.pending;
33
+ }
34
+ async refresh() {
35
+ this.token = undefined;
36
+ this.expiresAt = 0;
37
+ return this.getToken();
38
+ }
39
+ async exchange() {
40
+ const response = await fetch(this.exchangeUrl, {
41
+ method: "POST",
42
+ headers: { "content-type": "application/json", accept: "application/json" },
43
+ body: JSON.stringify({ gitlab_pat: this.gitlabPat }),
44
+ signal: AbortSignal.timeout(this.timeoutMs),
45
+ });
46
+ if (!response.ok) {
47
+ const detail = (await response.text().catch(() => "")).slice(0, 300);
48
+ throw new Error(`rivet token exchange failed: HTTP ${response.status}${detail ? ` ${detail}` : ""}`);
49
+ }
50
+ const data = (await response.json());
51
+ if (!data.access_token) {
52
+ throw new Error("rivet token exchange: no access_token in response");
53
+ }
54
+ const actual = (data.gitlab_url ?? "").replace(/\/+$/, "");
55
+ if (actual !== this.expectedGitlabUrl.replace(/\/+$/, "")) {
56
+ throw new Error(`rivet token exchange: GitLab instance mismatch (expected ${this.expectedGitlabUrl}, got ${actual || "none"})`);
57
+ }
58
+ const parsed = data.expires_at ? Date.parse(data.expires_at) : Number.NaN;
59
+ this.expiresAt = Number.isNaN(parsed) ? Date.now() + DEFAULT_TTL_MS : parsed;
60
+ this.token = data.access_token;
61
+ return this.token;
62
+ }
63
+ }
@@ -0,0 +1,79 @@
1
+ import assert from "node:assert/strict";
2
+ import { createServer } from "node:http";
3
+ import { describe, it } from "node:test";
4
+ import { RivetTokenProvider } from "./auth.js";
5
+ async function withServer(handler, run) {
6
+ const server = createServer(handler);
7
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
8
+ const port = server.address().port;
9
+ try {
10
+ await run(port);
11
+ }
12
+ finally {
13
+ await new Promise((resolve) => server.close(() => resolve()));
14
+ }
15
+ }
16
+ function provider(port, pat = "glpat-test", gitlabUrl = "https://gitlab.example") {
17
+ return new RivetTokenProvider(`http://127.0.0.1:${port}/exchange`, pat, gitlabUrl);
18
+ }
19
+ describe("RivetTokenProvider", () => {
20
+ it("exchanges PAT and caches the token", async () => {
21
+ let exchanges = 0;
22
+ await withServer((req, res) => {
23
+ exchanges += 1;
24
+ let body = "";
25
+ req.on("data", (chunk) => (body += chunk));
26
+ req.on("end", () => {
27
+ assert.equal(req.headers["content-type"], "application/json");
28
+ assert.equal(JSON.parse(body).gitlab_pat, "glpat-test");
29
+ res.setHeader("content-type", "application/json");
30
+ res.end(JSON.stringify({
31
+ access_token: `tok-${exchanges}`,
32
+ expires_at: "2030-01-01T00:00:00Z",
33
+ gitlab_url: "https://gitlab.example/",
34
+ }));
35
+ });
36
+ }, async (port) => {
37
+ const p = provider(port);
38
+ assert.equal(await p.getToken(), "tok-1");
39
+ assert.equal(await p.getToken(), "tok-1");
40
+ assert.equal(await p.refresh(), "tok-2");
41
+ assert.equal(exchanges, 2);
42
+ });
43
+ });
44
+ it("fails with HTTP status when PAT is invalid", async () => {
45
+ await withServer((_req, res) => {
46
+ res.statusCode = 401;
47
+ res.end('{"detail": "Invalid GitLab PAT"}');
48
+ }, async (port) => {
49
+ await assert.rejects(provider(port, "bad").getToken(), /HTTP 401/);
50
+ });
51
+ });
52
+ it("rejects exchange from a foreign GitLab instance", async () => {
53
+ await withServer((_req, res) => {
54
+ res.setHeader("content-type", "application/json");
55
+ res.end(JSON.stringify({ access_token: "tok", gitlab_url: "https://evil.example" }));
56
+ }, async (port) => {
57
+ await assert.rejects(provider(port).getToken(), /instance mismatch/);
58
+ });
59
+ });
60
+ it("refreshes after expiry instead of returning a stale token", async () => {
61
+ let exchanges = 0;
62
+ await withServer((_req, res) => {
63
+ exchanges += 1;
64
+ res.setHeader("content-type", "application/json");
65
+ // TTL 20 секунд < REFRESH_MARGIN (30s): второй вызов обязан пойти в exchange
66
+ res.end(JSON.stringify({
67
+ access_token: `tok-${exchanges}`,
68
+ expires_at: new Date(Date.now() + 20_000).toISOString(),
69
+ gitlab_url: "https://gitlab.example",
70
+ }));
71
+ }, async (port) => {
72
+ const p = provider(port);
73
+ const first = await p.getToken();
74
+ const second = await p.getToken();
75
+ assert.notEqual(first, second);
76
+ assert.equal(exchanges, 2);
77
+ });
78
+ });
79
+ });
package/dist/cli.js ADDED
@@ -0,0 +1,62 @@
1
+ #!/usr/bin/env node
2
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
3
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
+ import { CallToolRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, ReadResourceRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
5
+ import { RivetTokenProvider } from "./auth.js";
6
+ import { RemoteRivet } from "./remote.js";
7
+ const CLIENT_INFO = { name: "rivet-mcp-bridge", version: "1.0.0" };
8
+ const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
9
+ function requiredEnv(name) {
10
+ const value = process.env[name];
11
+ if (!value) {
12
+ throw new Error(`missing required environment variable: ${name}`);
13
+ }
14
+ return value;
15
+ }
16
+ /** HTTPS обязателен; http допускается только для локального dev-стенда. */
17
+ function assertSecureUrl(name, raw) {
18
+ const url = new URL(raw);
19
+ const isLocal = LOCAL_HOSTS.has(url.hostname);
20
+ if (url.protocol === "http:" && !isLocal) {
21
+ throw new Error(`${name} must use https:// (got ${url.protocol}//${url.hostname}); http allowed only for localhost`);
22
+ }
23
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
24
+ throw new Error(`${name} must be an http(s) URL`);
25
+ }
26
+ return url;
27
+ }
28
+ function trimmedUrl(value) {
29
+ return value.replace(/\/+$/, "");
30
+ }
31
+ async function main() {
32
+ const rivetBase = trimmedUrl(requiredEnv("RIVET_URL"));
33
+ const gitlabUrl = trimmedUrl(requiredEnv("GITLAB_URL"));
34
+ assertSecureUrl("RIVET_URL", rivetBase);
35
+ assertSecureUrl("GITLAB_URL", gitlabUrl);
36
+ const tokens = new RivetTokenProvider(`${rivetBase}/api/auth/gitlab/exchange`, requiredEnv("GITLAB_TOKEN"), gitlabUrl);
37
+ // trailing slash важен: POST /mcp без него даёт 307-редирект
38
+ const remote = new RemoteRivet(`${rivetBase}/mcp/`, tokens);
39
+ // pre-flight: ошибка PAT/адресов видна при старте процесса, а не на первом tools/call
40
+ await remote.connect();
41
+ console.error(`rivet-mcp-bridge: connected to ${rivetBase}/mcp/ (gitlab: ${gitlabUrl})`);
42
+ const server = new Server({ ...CLIENT_INFO }, {
43
+ capabilities: { tools: {}, resources: {} },
44
+ });
45
+ server.setRequestHandler(ListToolsRequestSchema, () => remote.call((c) => c.listTools()));
46
+ server.setRequestHandler(CallToolRequestSchema, ({ params }) => remote.call((c) => c.callTool({ name: params.name, arguments: params.arguments })));
47
+ server.setRequestHandler(ListResourcesRequestSchema, () => remote.call((c) => c.listResources()));
48
+ server.setRequestHandler(ReadResourceRequestSchema, ({ params }) => remote.call((c) => c.readResource({ uri: params.uri })));
49
+ const shutdown = async () => {
50
+ await remote.close();
51
+ await server.close();
52
+ process.exit(0);
53
+ };
54
+ process.on("SIGINT", () => void shutdown());
55
+ process.on("SIGTERM", () => void shutdown());
56
+ await server.connect(new StdioServerTransport());
57
+ }
58
+ main().catch((error) => {
59
+ const message = error instanceof Error ? error.message : String(error);
60
+ console.error(`rivet-mcp-bridge: ${message}`);
61
+ process.exitCode = 1;
62
+ });
package/dist/remote.js ADDED
@@ -0,0 +1,58 @@
1
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
3
+ import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js";
4
+ const CLIENT_INFO = { name: "rivet-mcp-bridge", version: "1.0.0" };
5
+ /** Подключение к Streamable HTTP /mcp с Bearer-токеном и reconnect'ом при 401. */
6
+ export class RemoteRivet {
7
+ mcpUrl;
8
+ tokens;
9
+ client;
10
+ constructor(mcpUrl, tokens) {
11
+ this.mcpUrl = mcpUrl;
12
+ this.tokens = tokens;
13
+ }
14
+ async connect() {
15
+ const token = await this.tokens.getToken();
16
+ const transport = new StreamableHTTPClientTransport(new URL(this.mcpUrl), {
17
+ requestInit: { headers: { authorization: `Bearer ${token}` } },
18
+ });
19
+ const client = new Client({ ...CLIENT_INFO }, { capabilities: {} });
20
+ await client.connect(transport);
21
+ this.client = client;
22
+ }
23
+ /**
24
+ * Выполнить вызов к rivet; при 401 (истёк токен) — обменять PAT заново,
25
+ * переподключиться и повторить ровно один раз.
26
+ */
27
+ async call(action) {
28
+ if (!this.client) {
29
+ await this.connect();
30
+ }
31
+ let client = this.client;
32
+ try {
33
+ return await action(client);
34
+ }
35
+ catch (error) {
36
+ if (!(error instanceof UnauthorizedError)) {
37
+ throw error;
38
+ }
39
+ await this.tokens.refresh();
40
+ await this.close();
41
+ await this.connect();
42
+ client = this.client;
43
+ return await action(client);
44
+ }
45
+ }
46
+ async close() {
47
+ if (!this.client) {
48
+ return;
49
+ }
50
+ try {
51
+ await this.client.close();
52
+ }
53
+ catch {
54
+ // соединение уже закрыто
55
+ }
56
+ this.client = undefined;
57
+ }
58
+ }
package/package.json CHANGED
@@ -1,6 +1,28 @@
1
1
  {
2
2
  "name": "rivet-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "stdio MCP bridge for the Rivet code-retrieval platform: exchanges a GitLab PAT for a short-lived MCP token and forwards to the Rivet Streamable HTTP endpoint",
5
+ "type": "module",
6
+ "bin": {
7
+ "rivet-mcp": "dist/cli.js"
8
+ },
9
+ "files": [
10
+ "dist",
11
+ "README.md"
12
+ ],
13
+ "scripts": {
14
+ "build": "tsc -p tsconfig.json",
15
+ "prepack": "npm run build",
16
+ "test": "npm run build && node --test dist/test/*.test.js"
17
+ },
18
+ "engines": {
19
+ "node": ">=20.11.0"
20
+ },
21
+ "dependencies": {
22
+ "@modelcontextprotocol/sdk": "^1.32.2"
23
+ },
24
+ "devDependencies": {
25
+ "@types/node": "^22.0.0",
26
+ "typescript": "^5.7.0"
27
+ }
28
+ }