rivet-mcp 0.0.0-stage → 1.0.1
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 +65 -2
- package/dist/auth.js +63 -0
- package/dist/cli.js +66 -0
- package/dist/remote.js +68 -0
- package/package.json +27 -4
package/README.md
CHANGED
|
@@ -1,3 +1,66 @@
|
|
|
1
|
-
#
|
|
1
|
+
# rivet-mcp
|
|
2
2
|
|
|
3
|
-
|
|
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
|
+
}
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { pathToFileURL } from "node:url";
|
|
3
|
+
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
4
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
5
|
+
import { CallToolRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, ReadResourceRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
|
|
6
|
+
import { RivetTokenProvider } from "./auth.js";
|
|
7
|
+
import { RemoteRivet } from "./remote.js";
|
|
8
|
+
const CLIENT_INFO = { name: "rivet-mcp-bridge", version: "1.0.0" };
|
|
9
|
+
const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
|
|
10
|
+
function requiredEnv(name) {
|
|
11
|
+
const value = process.env[name];
|
|
12
|
+
if (!value) {
|
|
13
|
+
throw new Error(`missing required environment variable: ${name}`);
|
|
14
|
+
}
|
|
15
|
+
return value;
|
|
16
|
+
}
|
|
17
|
+
/** HTTPS обязателен; http допускается только для локального dev-стенда. */
|
|
18
|
+
export function assertSecureUrl(name, raw) {
|
|
19
|
+
const url = new URL(raw);
|
|
20
|
+
const isLocal = LOCAL_HOSTS.has(url.hostname);
|
|
21
|
+
if (url.protocol === "http:" && !isLocal) {
|
|
22
|
+
throw new Error(`${name} must use https:// (got ${url.protocol}//${url.hostname}); http allowed only for localhost`);
|
|
23
|
+
}
|
|
24
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
25
|
+
throw new Error(`${name} must be an http(s) URL`);
|
|
26
|
+
}
|
|
27
|
+
return url;
|
|
28
|
+
}
|
|
29
|
+
function trimmedUrl(value) {
|
|
30
|
+
return value.replace(/\/+$/, "");
|
|
31
|
+
}
|
|
32
|
+
async function main() {
|
|
33
|
+
const rivetBase = trimmedUrl(requiredEnv("RIVET_URL"));
|
|
34
|
+
const gitlabUrl = trimmedUrl(requiredEnv("GITLAB_URL"));
|
|
35
|
+
assertSecureUrl("RIVET_URL", rivetBase);
|
|
36
|
+
assertSecureUrl("GITLAB_URL", gitlabUrl);
|
|
37
|
+
const tokens = new RivetTokenProvider(`${rivetBase}/api/auth/gitlab/exchange`, requiredEnv("GITLAB_TOKEN"), gitlabUrl);
|
|
38
|
+
// trailing slash важен: POST /mcp без него даёт 307-редирект
|
|
39
|
+
const remote = new RemoteRivet(`${rivetBase}/mcp/`, tokens);
|
|
40
|
+
// pre-flight: ошибка PAT/адресов видна при старте процесса, а не на первом tools/call
|
|
41
|
+
await remote.connect();
|
|
42
|
+
console.error(`rivet-mcp-bridge: connected to ${rivetBase}/mcp/ (gitlab: ${gitlabUrl})`);
|
|
43
|
+
const server = new Server({ ...CLIENT_INFO }, {
|
|
44
|
+
capabilities: { tools: {}, resources: {} },
|
|
45
|
+
});
|
|
46
|
+
server.setRequestHandler(ListToolsRequestSchema, () => remote.call((c) => c.listTools()));
|
|
47
|
+
server.setRequestHandler(CallToolRequestSchema, ({ params }) => remote.call((c) => c.callTool({ name: params.name, arguments: params.arguments })));
|
|
48
|
+
server.setRequestHandler(ListResourcesRequestSchema, () => remote.call((c) => c.listResources()));
|
|
49
|
+
server.setRequestHandler(ReadResourceRequestSchema, ({ params }) => remote.call((c) => c.readResource({ uri: params.uri })));
|
|
50
|
+
const shutdown = async () => {
|
|
51
|
+
await remote.close();
|
|
52
|
+
await server.close();
|
|
53
|
+
process.exit(0);
|
|
54
|
+
};
|
|
55
|
+
process.on("SIGINT", () => void shutdown());
|
|
56
|
+
process.on("SIGTERM", () => void shutdown());
|
|
57
|
+
await server.connect(new StdioServerTransport());
|
|
58
|
+
}
|
|
59
|
+
// main() — только при запуске файла как CLI, не при import из тестов
|
|
60
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
61
|
+
main().catch((error) => {
|
|
62
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
63
|
+
console.error(`rivet-mcp-bridge: ${message}`);
|
|
64
|
+
process.exitCode = 1;
|
|
65
|
+
});
|
|
66
|
+
}
|
package/dist/remote.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
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
|
+
reconnectPromise;
|
|
11
|
+
constructor(mcpUrl, tokens) {
|
|
12
|
+
this.mcpUrl = mcpUrl;
|
|
13
|
+
this.tokens = tokens;
|
|
14
|
+
}
|
|
15
|
+
async connect() {
|
|
16
|
+
const token = await this.tokens.getToken();
|
|
17
|
+
const transport = new StreamableHTTPClientTransport(new URL(this.mcpUrl), {
|
|
18
|
+
requestInit: { headers: { authorization: `Bearer ${token}` } },
|
|
19
|
+
});
|
|
20
|
+
const client = new Client({ ...CLIENT_INFO }, { capabilities: {} });
|
|
21
|
+
await client.connect(transport);
|
|
22
|
+
this.client = client;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Выполнить вызов к rivet; при 401 (истёк токен) — один общий reconnect
|
|
26
|
+
* (single-flight: параллельные вызовы ждут тот же reconnect) и повтор ровно один раз.
|
|
27
|
+
*/
|
|
28
|
+
async call(action) {
|
|
29
|
+
if (!this.client) {
|
|
30
|
+
await this.reconnectOnce();
|
|
31
|
+
}
|
|
32
|
+
try {
|
|
33
|
+
return await action(this.client);
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
if (!(error instanceof UnauthorizedError)) {
|
|
37
|
+
throw error;
|
|
38
|
+
}
|
|
39
|
+
await this.reconnectOnce();
|
|
40
|
+
return await action(this.client);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/** Один reconnect на все параллельные вызовы; завершившиеся ошибкой — получают её все. */
|
|
44
|
+
reconnectOnce() {
|
|
45
|
+
if (!this.reconnectPromise) {
|
|
46
|
+
this.reconnectPromise = (async () => {
|
|
47
|
+
await this.tokens.refresh();
|
|
48
|
+
await this.close();
|
|
49
|
+
await this.connect();
|
|
50
|
+
})().finally(() => {
|
|
51
|
+
this.reconnectPromise = undefined;
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
return this.reconnectPromise;
|
|
55
|
+
}
|
|
56
|
+
async close() {
|
|
57
|
+
if (!this.client) {
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
try {
|
|
61
|
+
await this.client.close();
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
// соединение уже закрыто
|
|
65
|
+
}
|
|
66
|
+
this.client = undefined;
|
|
67
|
+
}
|
|
68
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,29 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "rivet-mcp",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.1",
|
|
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": "rm -rf dist && tsc -p tsconfig.json",
|
|
15
|
+
"build:test": "tsc -p tsconfig.test.json",
|
|
16
|
+
"prepack": "npm run build",
|
|
17
|
+
"test": "npm run build && npm run build:test && node --test dist/*.test.js"
|
|
18
|
+
},
|
|
19
|
+
"engines": {
|
|
20
|
+
"node": ">=20.11.0"
|
|
21
|
+
},
|
|
22
|
+
"dependencies": {
|
|
23
|
+
"@modelcontextprotocol/sdk": "^1.32.2"
|
|
24
|
+
},
|
|
25
|
+
"devDependencies": {
|
|
26
|
+
"@types/node": "^22.0.0",
|
|
27
|
+
"typescript": "^5.7.0"
|
|
28
|
+
}
|
|
29
|
+
}
|