@aidenhq/sdk 0.1.1 → 0.3.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 +9 -4
- package/dist/bin/aidenhq-module-test.d.ts +2 -0
- package/dist/bin/aidenhq-module-test.js +0 -1
- package/dist/src/caller.d.ts +27 -0
- package/dist/src/caller.js +53 -54
- package/dist/src/engine-io.d.ts +35 -0
- package/dist/src/engine-io.js +103 -93
- package/dist/src/executor.d.ts +56 -0
- package/dist/src/executor.js +65 -65
- package/dist/src/fence.d.ts +3 -0
- package/dist/src/fence.js +5 -6
- package/dist/src/judge.d.ts +31 -0
- package/dist/src/judge.js +89 -0
- package/dist/src/kit.d.ts +21 -0
- package/dist/src/kit.js +56 -54
- package/dist/src/progress.d.ts +16 -0
- package/dist/src/progress.js +36 -39
- package/dist/src/reviewer.d.ts +70 -0
- package/dist/src/reviewer.js +48 -60
- package/dist/src/source-store.d.ts +67 -0
- package/dist/src/source-store.js +226 -0
- package/dist/src/types.d.ts +93 -0
- package/dist/src/types.js +1 -31
- package/dist/src/vendor/oauth.d.ts +85 -0
- package/dist/src/vendor/oauth.js +275 -0
- package/dist/src/vendor/proxy.d.ts +57 -0
- package/dist/src/vendor/proxy.js +270 -0
- package/package.json +43 -4
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
// How a vendor MCP connection (src/vendor/proxy.ts) reaches its upstream as the owner: OAuth 2.1 with PKCE, started from
|
|
2
|
+
// the board (its Connect sends the browser here and back to the board's callback, at its https address or on loopback), with the scopes the owner picks
|
|
3
|
+
// there. The client is registered dynamically (RFC 7591) or is one the owner made in the vendor (HubSpot, Slack). Only this
|
|
4
|
+
// service sees the tokens: the pair lives in /state/token.json (0600), refreshed here, rotated pairs written back atomically.
|
|
5
|
+
//
|
|
6
|
+
// Vendor connections import it as @aidenhq/sdk/vendor/oauth.
|
|
7
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
8
|
+
import { chmodSync, existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
9
|
+
import { dirname, join } from "node:path";
|
|
10
|
+
export class AuthError extends Error {
|
|
11
|
+
}
|
|
12
|
+
export class SignInError extends Error {
|
|
13
|
+
}
|
|
14
|
+
/** A connection that signs in to nothing (a local server), with fixed headers. */
|
|
15
|
+
export function staticAuth(headers = {}) {
|
|
16
|
+
const since = new Date().toISOString();
|
|
17
|
+
return { headers: async () => headers, refresh: async () => { }, status: () => ({ state: "none", since }), mark: () => { }, signedIn: () => true };
|
|
18
|
+
}
|
|
19
|
+
const LOOPBACK = /^http:\/\/(127\.0\.0\.1|localhost)(:\d+)?\/[\w/-]*$/;
|
|
20
|
+
/** A redirect this sign-in may send: a loopback callback (a tunnel), or a callback on the board's https origin. */
|
|
21
|
+
export function redirectAllowed(redirectUri, boardUrl = process.env.BOARD_URL ?? "") {
|
|
22
|
+
if (LOOPBACK.test(redirectUri))
|
|
23
|
+
return true;
|
|
24
|
+
const board = URL.canParse(boardUrl) ? new URL(boardUrl) : undefined;
|
|
25
|
+
if (board?.protocol !== "https:" || !redirectUri.startsWith(`${board.origin}/`))
|
|
26
|
+
return false;
|
|
27
|
+
return /^\/[\w/-]*$/.test(redirectUri.slice(board.origin.length));
|
|
28
|
+
}
|
|
29
|
+
const strings = (v) => (Array.isArray(v) ? v.filter((s) => typeof s === "string") : undefined);
|
|
30
|
+
/** The owner's OAuth sign-in to a vendor's MCP server. */
|
|
31
|
+
export function oauth(o) {
|
|
32
|
+
const fetchImpl = o.fetchImpl ?? fetch;
|
|
33
|
+
const tokenPath = join(o.stateDir, "token.json");
|
|
34
|
+
const clientPath = join(o.stateDir, "client.json");
|
|
35
|
+
// The resource a token is for (RFC 8707): the MCP endpoint without its query (Atlassian's ?tools=all).
|
|
36
|
+
const resourceOf = () => { if (o.resource === false)
|
|
37
|
+
return undefined; const u = new URL(o.mcpUrl); return u.origin + u.pathname; };
|
|
38
|
+
const pending = new Map();
|
|
39
|
+
let token;
|
|
40
|
+
let refreshing;
|
|
41
|
+
let status = { state: "unknown", since: new Date().toISOString() };
|
|
42
|
+
const json = async (url, init) => {
|
|
43
|
+
const res = await fetchImpl(url, { ...init, signal: AbortSignal.timeout(15_000) });
|
|
44
|
+
return { ok: res.ok, status: res.status, body: (await res.json().catch(() => ({}))) };
|
|
45
|
+
};
|
|
46
|
+
/** A token answer as StoredToken fields; a refusal throws its error. */
|
|
47
|
+
function parse(raw, now = Date.now()) {
|
|
48
|
+
const a = o.tokenAnswer ? o.tokenAnswer(raw) : raw;
|
|
49
|
+
if (typeof a.error === "string" || a.ok === false)
|
|
50
|
+
throw new AuthError(`${o.name} OAuth error: ${String(a.error ?? "refused")}`);
|
|
51
|
+
if (typeof a.access_token !== "string" || !a.access_token)
|
|
52
|
+
throw new AuthError(`${o.name} OAuth answer had no access token`);
|
|
53
|
+
const expiresIn = Number(a.expires_in);
|
|
54
|
+
const { expires_in: _e, ok: _o, ...rest } = a;
|
|
55
|
+
return {
|
|
56
|
+
...rest,
|
|
57
|
+
access_token: a.access_token,
|
|
58
|
+
refresh_token: typeof a.refresh_token === "string" ? a.refresh_token : undefined,
|
|
59
|
+
expires_at: Number.isFinite(expiresIn) && expiresIn > 0 ? now + expiresIn * 1000 : undefined,
|
|
60
|
+
scope: typeof a.scope === "string" ? a.scope : undefined,
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
function mark(state, detail) {
|
|
64
|
+
if (status.state === state && status.detail === detail)
|
|
65
|
+
return;
|
|
66
|
+
status = { state, since: new Date().toISOString(), ...(detail ? { detail } : {}) };
|
|
67
|
+
}
|
|
68
|
+
function load() {
|
|
69
|
+
if (!token) {
|
|
70
|
+
if (!existsSync(tokenPath))
|
|
71
|
+
throw new AuthError(`${o.name} isn't connected yet (Connect on the board)`);
|
|
72
|
+
token = JSON.parse(readFileSync(tokenPath, "utf8"));
|
|
73
|
+
}
|
|
74
|
+
return token;
|
|
75
|
+
}
|
|
76
|
+
function save(t) {
|
|
77
|
+
const tmp = join(dirname(tokenPath), `.token.${process.pid}.tmp`);
|
|
78
|
+
writeFileSync(tmp, JSON.stringify(t, null, 2), { mode: 0o600 });
|
|
79
|
+
chmodSync(tmp, 0o600);
|
|
80
|
+
renameSync(tmp, tokenPath);
|
|
81
|
+
token = t;
|
|
82
|
+
}
|
|
83
|
+
async function doRefresh() {
|
|
84
|
+
const t = load();
|
|
85
|
+
const endpoint = t.token_endpoint ?? o.endpoints?.token;
|
|
86
|
+
const clientId = t.client_id ?? o.client?.()?.id;
|
|
87
|
+
if (!t.refresh_token || !endpoint || !clientId) {
|
|
88
|
+
mark("expired", "the sign-in has no refresh token");
|
|
89
|
+
throw new AuthError(`${o.name} token expired and can't be refreshed (Reconnect on the board)`);
|
|
90
|
+
}
|
|
91
|
+
const body = new URLSearchParams({ grant_type: "refresh_token", refresh_token: t.refresh_token, client_id: clientId });
|
|
92
|
+
const secret = t.client_secret ?? o.client?.()?.secret;
|
|
93
|
+
if (secret)
|
|
94
|
+
body.set("client_secret", secret);
|
|
95
|
+
if (t.resource)
|
|
96
|
+
body.set("resource", t.resource);
|
|
97
|
+
const res = await fetchImpl(endpoint, { method: "POST", body, signal: AbortSignal.timeout(15_000) });
|
|
98
|
+
const answer = (await res.json().catch(() => ({})));
|
|
99
|
+
let next;
|
|
100
|
+
try {
|
|
101
|
+
if (!res.ok && typeof answer.error !== "string")
|
|
102
|
+
throw new AuthError(`${o.name} token endpoint answered ${res.status}`);
|
|
103
|
+
next = parse(answer);
|
|
104
|
+
}
|
|
105
|
+
catch (err) {
|
|
106
|
+
// A refusal (invalid_grant and the like) needs the owner; a 5xx is the vendor's problem and may pass.
|
|
107
|
+
if (res.status < 500)
|
|
108
|
+
mark("expired", String(err.message));
|
|
109
|
+
throw err;
|
|
110
|
+
}
|
|
111
|
+
save({ ...t, ...next, refresh_token: next.refresh_token ?? t.refresh_token });
|
|
112
|
+
return token;
|
|
113
|
+
}
|
|
114
|
+
const refresh = () => (refreshing ??= doRefresh().finally(() => (refreshing = undefined)));
|
|
115
|
+
/** The vendor's endpoints and the scopes it lists: the server's 401 names its resource metadata (the MCP way), else the well-known paths. */
|
|
116
|
+
async function discover() {
|
|
117
|
+
const listed = o.scopes?.supported;
|
|
118
|
+
if (o.endpoints)
|
|
119
|
+
return { ...o.endpoints, issuer: new URL(o.endpoints.authorize).origin, supported: listed ?? [], offline: false };
|
|
120
|
+
const mcp = new URL(o.mcpUrl);
|
|
121
|
+
const path = mcp.pathname.replace(/\/$/, "");
|
|
122
|
+
const probe = await fetchImpl(o.mcpUrl, {
|
|
123
|
+
method: "POST",
|
|
124
|
+
headers: { "content-type": "application/json", accept: "application/json, text/event-stream", ...o.headers },
|
|
125
|
+
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "ping" }),
|
|
126
|
+
signal: AbortSignal.timeout(15_000),
|
|
127
|
+
}).catch(() => undefined);
|
|
128
|
+
const named = /resource_metadata="([^"]+)"/.exec(probe?.headers.get("www-authenticate") ?? "")?.[1];
|
|
129
|
+
let issuer = mcp.origin;
|
|
130
|
+
let resourceScopes;
|
|
131
|
+
for (const u of [...(named ? [named] : []), `${mcp.origin}/.well-known/oauth-protected-resource${path}`, `${mcp.origin}/.well-known/oauth-protected-resource`]) {
|
|
132
|
+
const r = await json(u).catch(() => undefined);
|
|
133
|
+
const servers = r?.ok ? strings(r.body.authorization_servers) : undefined;
|
|
134
|
+
if (servers?.[0]) {
|
|
135
|
+
issuer = servers[0].replace(/\/$/, "");
|
|
136
|
+
resourceScopes = strings(r.body.scopes_supported);
|
|
137
|
+
break;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
const is = new URL(issuer);
|
|
141
|
+
const isPath = is.pathname.replace(/\/$/, "");
|
|
142
|
+
for (const u of [`${is.origin}/.well-known/oauth-authorization-server${isPath}`, `${is.origin}${isPath}/.well-known/openid-configuration`, `${is.origin}/.well-known/oauth-authorization-server`]) {
|
|
143
|
+
const r = await json(u).catch(() => undefined);
|
|
144
|
+
if (r?.ok && typeof r.body.authorization_endpoint === "string" && typeof r.body.token_endpoint === "string") {
|
|
145
|
+
const offered = strings(r.body.scopes_supported) ?? [];
|
|
146
|
+
return {
|
|
147
|
+
authorize: r.body.authorization_endpoint,
|
|
148
|
+
token: r.body.token_endpoint,
|
|
149
|
+
...(typeof r.body.registration_endpoint === "string" ? { registration: r.body.registration_endpoint } : {}),
|
|
150
|
+
issuer,
|
|
151
|
+
// What the owner may pick: the resource's own list, else the server's (offline_access is added on its own).
|
|
152
|
+
supported: (listed ?? (resourceScopes?.length ? resourceScopes : offered)).filter((s) => s !== "offline_access"),
|
|
153
|
+
// Without offline_access there may be no refresh token, and the sign-in would end with the first access token.
|
|
154
|
+
offline: offered.includes("offline_access") || Boolean(resourceScopes?.includes("offline_access")),
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
throw new SignInError(`couldn't find ${o.name}'s sign-in server for ${o.mcpUrl}`);
|
|
159
|
+
}
|
|
160
|
+
async function client(ep, redirectUri) {
|
|
161
|
+
if (o.client) {
|
|
162
|
+
const c = o.client();
|
|
163
|
+
if (!c)
|
|
164
|
+
throw new SignInError(`${o.name}'s client isn't set up: add its client id (and secret) on the setup page`);
|
|
165
|
+
return c;
|
|
166
|
+
}
|
|
167
|
+
const saved = existsSync(clientPath) ? JSON.parse(readFileSync(clientPath, "utf8")) : undefined;
|
|
168
|
+
if (saved?.client_id && saved.redirect_uri === redirectUri && saved.issuer === ep.issuer)
|
|
169
|
+
return { id: saved.client_id, ...(saved.client_secret ? { secret: saved.client_secret } : {}) };
|
|
170
|
+
if (!ep.registration)
|
|
171
|
+
throw new SignInError(`${o.name} doesn't offer client registration (ask an admin to enable its OAuth authorization server)`);
|
|
172
|
+
const r = await json(ep.registration, {
|
|
173
|
+
method: "POST",
|
|
174
|
+
headers: { "content-type": "application/json" },
|
|
175
|
+
body: JSON.stringify({ client_name: "AidenHQ", redirect_uris: [redirectUri], grant_types: ["authorization_code", "refresh_token"], response_types: ["code"], token_endpoint_auth_method: "none" }),
|
|
176
|
+
});
|
|
177
|
+
if (!r.ok || typeof r.body.client_id !== "string")
|
|
178
|
+
throw new SignInError(`${o.name} refused to register AidenHQ (${String(r.body.error_description ?? r.body.error ?? r.status).slice(0, 200)})`);
|
|
179
|
+
const secret = typeof r.body.client_secret === "string" ? r.body.client_secret : undefined;
|
|
180
|
+
writeFileSync(clientPath, JSON.stringify({ client_id: r.body.client_id, ...(secret ? { client_secret: secret } : {}), redirect_uri: redirectUri, issuer: ep.issuer }, null, 2), { mode: 0o600 });
|
|
181
|
+
chmodSync(clientPath, 0o600);
|
|
182
|
+
return { id: r.body.client_id, ...(secret ? { secret } : {}) };
|
|
183
|
+
}
|
|
184
|
+
const recommended = (supported) => {
|
|
185
|
+
const want = o.scopes?.recommended;
|
|
186
|
+
return want ? want.filter((s) => !supported.length || supported.includes(s)) : supported;
|
|
187
|
+
};
|
|
188
|
+
const signIn = {
|
|
189
|
+
async scopes() {
|
|
190
|
+
const { supported } = await discover();
|
|
191
|
+
return { supported, recommended: recommended(supported) };
|
|
192
|
+
},
|
|
193
|
+
/** The vendor's sign-in URL, asking for `scopes` (the owner's pick; default: the recommended ones). */
|
|
194
|
+
async start(redirectUri, scopes) {
|
|
195
|
+
if (!redirectAllowed(redirectUri, o.boardUrl))
|
|
196
|
+
throw new SignInError("redirect must be a loopback address or the board's own https address");
|
|
197
|
+
const ep = await discover();
|
|
198
|
+
const extra = (scopes ?? []).filter((s) => s !== "offline_access" && !ep.supported.includes(s));
|
|
199
|
+
if (extra.length)
|
|
200
|
+
throw new SignInError(`${o.name} doesn't offer ${extra.join(", ")}`);
|
|
201
|
+
const picked = (scopes ?? recommended(ep.supported)).filter((s) => s !== "offline_access");
|
|
202
|
+
const asked = picked.length && ep.offline ? [...picked, "offline_access"] : picked;
|
|
203
|
+
const c = await client(ep, redirectUri);
|
|
204
|
+
const now = Date.now();
|
|
205
|
+
for (const [k, p] of pending)
|
|
206
|
+
if (p.expires < now)
|
|
207
|
+
pending.delete(k);
|
|
208
|
+
const verifier = randomBytes(48).toString("base64url");
|
|
209
|
+
const state = randomBytes(24).toString("base64url");
|
|
210
|
+
pending.set(state, { verifier, redirectUri, ep, client: c, expires: now + 10 * 60_000 });
|
|
211
|
+
const resource = resourceOf();
|
|
212
|
+
const url = new URL(ep.authorize);
|
|
213
|
+
// Added to the endpoint's own query (Grafana's names the stack), never replacing it.
|
|
214
|
+
const params = {
|
|
215
|
+
response_type: "code",
|
|
216
|
+
client_id: c.id,
|
|
217
|
+
redirect_uri: redirectUri,
|
|
218
|
+
code_challenge: createHash("sha256").update(verifier).digest("base64url"),
|
|
219
|
+
code_challenge_method: "S256",
|
|
220
|
+
state,
|
|
221
|
+
...(resource ? { resource } : {}),
|
|
222
|
+
...(asked.length ? { scope: asked.join(o.scopes?.separator ?? " ") } : {}),
|
|
223
|
+
};
|
|
224
|
+
for (const [k, v] of Object.entries(params))
|
|
225
|
+
url.searchParams.set(k, v);
|
|
226
|
+
return { url: url.toString() };
|
|
227
|
+
},
|
|
228
|
+
async finish(state, code) {
|
|
229
|
+
const p = pending.get(state);
|
|
230
|
+
pending.delete(state);
|
|
231
|
+
if (!p || p.expires < Date.now())
|
|
232
|
+
throw new SignInError("this sign-in link expired or was already used; start again from the board");
|
|
233
|
+
const resource = resourceOf();
|
|
234
|
+
const body = new URLSearchParams({ grant_type: "authorization_code", code, client_id: p.client.id, code_verifier: p.verifier, redirect_uri: p.redirectUri, ...(resource ? { resource } : {}) });
|
|
235
|
+
if (p.client.secret)
|
|
236
|
+
body.set("client_secret", p.client.secret);
|
|
237
|
+
const r = await json(p.ep.token, { method: "POST", body });
|
|
238
|
+
let parsed;
|
|
239
|
+
try {
|
|
240
|
+
if (!r.ok && typeof r.body.error !== "string")
|
|
241
|
+
throw new AuthError(String(r.body.error_description ?? r.body.message ?? r.status));
|
|
242
|
+
parsed = parse(r.body);
|
|
243
|
+
}
|
|
244
|
+
catch (err) {
|
|
245
|
+
throw new SignInError(`${o.name} refused the sign-in: ${String(err.message).slice(0, 200)}`);
|
|
246
|
+
}
|
|
247
|
+
save({ ...parsed, client_id: p.client.id, ...(p.client.secret ? { client_secret: p.client.secret } : {}), token_endpoint: p.ep.token, ...(resource ? { resource } : {}) });
|
|
248
|
+
mark("ok");
|
|
249
|
+
},
|
|
250
|
+
};
|
|
251
|
+
return {
|
|
252
|
+
async headers() {
|
|
253
|
+
const t = load();
|
|
254
|
+
const access = !t.expires_at || t.expires_at - 120_000 > Date.now() ? t.access_token : (await refresh()).access_token;
|
|
255
|
+
return { ...o.headers, authorization: `Bearer ${access}` };
|
|
256
|
+
},
|
|
257
|
+
async refresh() {
|
|
258
|
+
await refresh();
|
|
259
|
+
},
|
|
260
|
+
status() {
|
|
261
|
+
if (!existsSync(tokenPath))
|
|
262
|
+
return { state: "missing", since: status.since };
|
|
263
|
+
const scope = (() => { try {
|
|
264
|
+
return load().scope;
|
|
265
|
+
}
|
|
266
|
+
catch {
|
|
267
|
+
return undefined;
|
|
268
|
+
} })();
|
|
269
|
+
return { ...status, ...(scope ? { scope } : {}) };
|
|
270
|
+
},
|
|
271
|
+
mark,
|
|
272
|
+
signedIn: () => existsSync(tokenPath),
|
|
273
|
+
signIn,
|
|
274
|
+
};
|
|
275
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { type IncomingMessage, type Server as HttpServer, type ServerResponse } from "node:http";
|
|
2
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
3
|
+
import { type CallToolResult, type Tool } from "@modelcontextprotocol/sdk/types.js";
|
|
4
|
+
import type { Logger } from "pino";
|
|
5
|
+
import { type Auth } from "./oauth.js";
|
|
6
|
+
/** A connection's own logic, where it has any. */
|
|
7
|
+
export interface Hooks {
|
|
8
|
+
/** After each connect (Jira: find the configured site); a throw fails the connect. */
|
|
9
|
+
connected?(client: Client, tools: Tool[]): Promise<void>;
|
|
10
|
+
/** The tools as agents see them (a pinned argument dropped from the schema, a lead line in a description). */
|
|
11
|
+
tools?(tools: Tool[]): Tool[];
|
|
12
|
+
/**
|
|
13
|
+
* The arguments sent upstream for one call of a tool the upstream lists (`tool`: its schema); a throw refuses the call.
|
|
14
|
+
* A pinned argument overrides whatever the caller sent.
|
|
15
|
+
*/
|
|
16
|
+
args?(name: string, args: Record<string, unknown>, tool: Tool): Record<string, unknown>;
|
|
17
|
+
/** Tools never listed or called (a real security rule; most connections have none). */
|
|
18
|
+
deny?: RegExp;
|
|
19
|
+
/** A tool's answer as it goes back (ClickHouse: cut to a size). */
|
|
20
|
+
result?(result: CallToolResult): CallToolResult;
|
|
21
|
+
/** Whether the upstream says a tool only reads. Default: it marks it readOnlyHint. */
|
|
22
|
+
isRead?(tool: Tool): boolean;
|
|
23
|
+
/** A problem that makes the connection unusable though signed in (Jira: the site isn't reachable). */
|
|
24
|
+
health?(): string | undefined;
|
|
25
|
+
}
|
|
26
|
+
export interface ProxyOptions {
|
|
27
|
+
/** The vendor's name in messages ("Glean"). */
|
|
28
|
+
name: string;
|
|
29
|
+
/** Unset: not configured yet (Connect on the board, or its setup flow, saves the value it needs). */
|
|
30
|
+
upstream: URL | undefined;
|
|
31
|
+
auth: Auth;
|
|
32
|
+
log: Logger;
|
|
33
|
+
/** The kernel's bearer for /mcp (the connection's service key). */
|
|
34
|
+
serviceKey?: string;
|
|
35
|
+
/** The read endpoint's bearer (jobs reach it only through the kernel); unset: no /mcp/read. */
|
|
36
|
+
readKey?: string;
|
|
37
|
+
/** The tools the module's manifest tags read: /mcp/read serves only these (and only those the upstream marks read-only). */
|
|
38
|
+
reads?: string[];
|
|
39
|
+
/** The board's bearer for /auth/*. */
|
|
40
|
+
authKey?: string;
|
|
41
|
+
/** Checks the kernel's caller assertion on a tools/call to /mcp; throws to refuse. */
|
|
42
|
+
caller(req: IncomingMessage): Promise<unknown>;
|
|
43
|
+
/** The MCP server's instructions to agents. */
|
|
44
|
+
instructions: string;
|
|
45
|
+
/** How long one tool call may take (ClickHouse's queries run up to two minutes); default: the MCP SDK's 60 seconds. */
|
|
46
|
+
callTimeoutMs?: number;
|
|
47
|
+
/** Remembers the tool list here (tools.json), for stand-ins while not connected. */
|
|
48
|
+
stateDir?: string;
|
|
49
|
+
hooks?: Hooks;
|
|
50
|
+
/** More routes on the same port (a write kind's executor); true when it answered. */
|
|
51
|
+
routes?(req: IncomingMessage, res: ServerResponse): Promise<boolean>;
|
|
52
|
+
}
|
|
53
|
+
export type VendorProxy = HttpServer & {
|
|
54
|
+
/** One tool call from this service's own code (a warehouse sync, an executor), through the same sign-in and hooks. */
|
|
55
|
+
call(name: string, args: Record<string, unknown>): Promise<CallToolResult>;
|
|
56
|
+
};
|
|
57
|
+
export declare function createVendorProxy(o: ProxyOptions): VendorProxy;
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
// A vendor's MCP server, passed through whole (owner, 2026-11-18: "every connection exposes the full upstream MCP"). Every
|
|
2
|
+
// upstream tool is listed and callable here; which ones an agent reaches is the kernel's: it lists and forwards only the
|
|
3
|
+
// tools the module's manifest tags (read, write, destructive, named) and the caller's grant names, files every write as a
|
|
4
|
+
// record its tier decides, and refuses everything else (tool-unlisted, no-grant). So a tool the vendor adds reaches nobody
|
|
5
|
+
// until a module change tags it. What stays here is what the kernel can't do:
|
|
6
|
+
// /mcp the kernel's calls for agents (its service key), each tools/call carrying its signed caller assertion;
|
|
7
|
+
// /mcp/read the kernel's calls for runner jobs (the read key): only tools the module's manifest tags read (`reads`, the
|
|
8
|
+
// READ_TOOLS its module.yaml sets from those tags) that the upstream also marks read-only (or the connection's
|
|
9
|
+
// read rule says are reads), so the jobs' token never reaches a write;
|
|
10
|
+
// /auth/* the board's sign-in (state, the scopes the owner may pick, start, finish), with the board's own key;
|
|
11
|
+
// /healthz whether it is connected.
|
|
12
|
+
// A connection adds only its real logic as hooks (a pinned argument, a site id, a deny rule) and its own routes (a write
|
|
13
|
+
// kind's executor). Not signed in: it still starts, lists the tools it saw last as stand-ins, and every call says how to
|
|
14
|
+
// connect (never a crash loop, never a silently empty tool list).
|
|
15
|
+
//
|
|
16
|
+
// Vendor connections import it as @aidenhq/sdk/vendor/proxy (the MCP SDK, zod and pino are theirs: peer dependencies).
|
|
17
|
+
import { timingSafeEqual } from "node:crypto";
|
|
18
|
+
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
19
|
+
import { createServer } from "node:http";
|
|
20
|
+
import { join } from "node:path";
|
|
21
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
22
|
+
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
23
|
+
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
24
|
+
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
25
|
+
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
26
|
+
import { z } from "zod";
|
|
27
|
+
import { AuthError, SignInError } from "./oauth.js";
|
|
28
|
+
// The upstream refused the token: refresh once and retry. A refresh that failed (AuthError) already marked what it meant
|
|
29
|
+
// (refused: expired; the vendor's 5xx: not), so it is never retried here.
|
|
30
|
+
const isAuthFailure = (err) => !(err instanceof AuthError) && /401|unauthori[sz]ed|unauthenticated|invalid_token|not_authenticated/i.test(String(err));
|
|
31
|
+
const refusal = (text) => ({ isError: true, content: [{ type: "text", text }] });
|
|
32
|
+
// Reads run unattended in Codex as read-only, closed-world tools. Every other tool is a write the kernel files as a record and
|
|
33
|
+
// its tier decides before anything runs; these hints only keep the harness from stopping to ask a person who isn't there.
|
|
34
|
+
const READ_HINTS = { readOnlyHint: true, destructiveHint: false, openWorldHint: false };
|
|
35
|
+
const WRITE_HINTS = { readOnlyHint: false, destructiveHint: false, openWorldHint: false };
|
|
36
|
+
export function createVendorProxy(o) {
|
|
37
|
+
const { log, auth, hooks = {} } = o;
|
|
38
|
+
const isRead = hooks.isRead ?? ((t) => t.annotations?.readOnlyHint === true);
|
|
39
|
+
const reads = new Set(o.reads ?? []);
|
|
40
|
+
// The read endpoint's rule: tagged read in the manifest, and a read by the upstream's word too. Either alone isn't enough.
|
|
41
|
+
const servesRead = (t) => reads.has(t.name) && isRead(t);
|
|
42
|
+
const denied = (name) => Boolean(hooks.deny?.test(name));
|
|
43
|
+
const cacheFile = o.stateDir ? join(o.stateDir, "tools.json") : undefined;
|
|
44
|
+
let upstream;
|
|
45
|
+
const notConnected = () => (!o.upstream ? `${o.name} isn't connected yet: the owner presses Connect on the board (Settings, Connections).` : auth.status().state === "expired" ? `${o.name}'s sign-in stopped working: the owner reconnects it on the board.` : `${o.name} isn't connected: the owner signs in from the board.`);
|
|
46
|
+
async function connect() {
|
|
47
|
+
if (!o.upstream)
|
|
48
|
+
throw new AuthError(notConnected());
|
|
49
|
+
const client = new Client({ name: `aidenhq-${o.name.toLowerCase()}-proxy`, version: "0.2.0" });
|
|
50
|
+
await client.connect(new StreamableHTTPClientTransport(o.upstream, { requestInit: { headers: await auth.headers() } }));
|
|
51
|
+
const tools = [];
|
|
52
|
+
let cursor;
|
|
53
|
+
do {
|
|
54
|
+
const page = await client.listTools(cursor ? { cursor } : undefined);
|
|
55
|
+
tools.push(...page.tools);
|
|
56
|
+
cursor = page.nextCursor;
|
|
57
|
+
} while (cursor);
|
|
58
|
+
await hooks.connected?.(client, tools);
|
|
59
|
+
upstream = { client, tools, at: Date.now() };
|
|
60
|
+
auth.mark("ok");
|
|
61
|
+
const names = tools.map((t) => t.name).filter((n) => !denied(n));
|
|
62
|
+
// The kernel lists only what the module tags; a name here it doesn't tag reaches nobody until a module change does.
|
|
63
|
+
log.info({ upstream_tools: tools.length, tools: names }, `connected to ${o.name}`);
|
|
64
|
+
if (cacheFile)
|
|
65
|
+
try {
|
|
66
|
+
writeFileSync(cacheFile, JSON.stringify(names));
|
|
67
|
+
}
|
|
68
|
+
catch { /* read-only state: no stand-ins */ }
|
|
69
|
+
return upstream;
|
|
70
|
+
}
|
|
71
|
+
async function reset(refresh) {
|
|
72
|
+
const old = upstream;
|
|
73
|
+
upstream = undefined;
|
|
74
|
+
await old?.client.close().catch(() => undefined);
|
|
75
|
+
if (refresh)
|
|
76
|
+
await auth.refresh();
|
|
77
|
+
await connect();
|
|
78
|
+
}
|
|
79
|
+
async function withUpstream(fn) {
|
|
80
|
+
// Reconnect every 30 minutes or after an auth failure (inside the try: a token revoked early fails connect() too).
|
|
81
|
+
try {
|
|
82
|
+
if (!upstream || Date.now() - upstream.at > 30 * 60_000)
|
|
83
|
+
await reset(false);
|
|
84
|
+
return await fn(upstream ?? (await connect()));
|
|
85
|
+
}
|
|
86
|
+
catch (err) {
|
|
87
|
+
if (!auth.signedIn() || !isAuthFailure(err))
|
|
88
|
+
throw err;
|
|
89
|
+
log.warn(`${o.name} rejected the token; refreshing and retrying once`);
|
|
90
|
+
try {
|
|
91
|
+
await reset(true);
|
|
92
|
+
return await fn(upstream ?? (await connect()));
|
|
93
|
+
}
|
|
94
|
+
catch (again) {
|
|
95
|
+
if (isAuthFailure(again))
|
|
96
|
+
auth.mark("expired", `${o.name} rejected a freshly refreshed token`);
|
|
97
|
+
throw again;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
/** The tools as listed: deny applied, the connection's view, and the harness hints. */
|
|
102
|
+
function shown(tools, readOnly) {
|
|
103
|
+
const kept = tools.filter((t) => !denied(t.name) && (!readOnly || servesRead(t)));
|
|
104
|
+
return (hooks.tools ? hooks.tools(kept) : kept).map((t) => ({ ...t, annotations: { ...(t.annotations ?? {}), ...(isRead(t) ? READ_HINTS : WRITE_HINTS) } }));
|
|
105
|
+
}
|
|
106
|
+
/** The names seen last, each answering how to connect: agents keep their tools while the sign-in is fixed. */
|
|
107
|
+
function standIns() {
|
|
108
|
+
const names = cacheFile && existsSync(cacheFile) ? JSON.parse(readFileSync(cacheFile, "utf8")) : [];
|
|
109
|
+
return names.map((name) => ({ name, description: notConnected(), inputSchema: { type: "object" } }));
|
|
110
|
+
}
|
|
111
|
+
async function call(name, args) {
|
|
112
|
+
if (denied(name))
|
|
113
|
+
throw new Error(`${name} is not available through AidenHQ`);
|
|
114
|
+
return withUpstream(async (u) => {
|
|
115
|
+
const tool = u.tools.find((t) => t.name === name);
|
|
116
|
+
// Only what the upstream lists: its schema is what the hooks pin arguments against.
|
|
117
|
+
if (!tool)
|
|
118
|
+
throw new Error(`${o.name} doesn't offer ${name}`);
|
|
119
|
+
const sent = hooks.args ? hooks.args(name, args, tool) : args;
|
|
120
|
+
const result = (await u.client.callTool({ name, arguments: sent }, undefined, o.callTimeoutMs ? { timeout: o.callTimeoutMs } : undefined));
|
|
121
|
+
return hooks.result ? hooks.result(result) : result;
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
function buildServer(readOnly) {
|
|
125
|
+
const server = new Server({ name: o.name.toLowerCase(), version: "0.2.0" }, { capabilities: { tools: {} }, instructions: o.instructions });
|
|
126
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
127
|
+
if (!o.upstream || !auth.signedIn())
|
|
128
|
+
return { tools: readOnly ? [] : standIns() };
|
|
129
|
+
try {
|
|
130
|
+
return { tools: await withUpstream(async (u) => shown(u.tools, readOnly)) };
|
|
131
|
+
}
|
|
132
|
+
catch (err) {
|
|
133
|
+
log.error({ err: String(err).slice(0, 300) }, `listing ${o.name} tools failed`);
|
|
134
|
+
return { tools: readOnly ? [] : standIns() };
|
|
135
|
+
}
|
|
136
|
+
});
|
|
137
|
+
server.setRequestHandler(CallToolRequestSchema, async (req) => {
|
|
138
|
+
const name = req.params.name;
|
|
139
|
+
if (denied(name)) {
|
|
140
|
+
log.warn({ tool: name }, "refused a denied tool");
|
|
141
|
+
return refusal(`Tool ${name} is not available through AidenHQ.`);
|
|
142
|
+
}
|
|
143
|
+
if (!o.upstream || !auth.signedIn())
|
|
144
|
+
return refusal(notConnected());
|
|
145
|
+
try {
|
|
146
|
+
if (readOnly) {
|
|
147
|
+
const tool = (await withUpstream(async (u) => u.tools)).find((t) => t.name === name);
|
|
148
|
+
if (!tool || !servesRead(tool)) {
|
|
149
|
+
log.warn({ tool: name }, "refused a write on the read endpoint");
|
|
150
|
+
return refusal(`Tool ${name} is not a read: the read endpoint serves reads only.`);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return await call(name, req.params.arguments ?? {});
|
|
154
|
+
}
|
|
155
|
+
catch (err) {
|
|
156
|
+
const signIn = err instanceof AuthError || isAuthFailure(err) || auth.status().state === "expired";
|
|
157
|
+
log.warn({ tool: name, err: String(err).slice(0, 300) }, `${o.name} tool failed`);
|
|
158
|
+
return refusal(signIn ? `${notConnected()} (${String(err.message).slice(0, 200)})` : `${o.name} error: ${String(err.message).slice(0, 300)}`);
|
|
159
|
+
}
|
|
160
|
+
});
|
|
161
|
+
return server;
|
|
162
|
+
}
|
|
163
|
+
const bearer = (req, token) => {
|
|
164
|
+
if (!token)
|
|
165
|
+
return false;
|
|
166
|
+
const presented = Buffer.from((req.headers.authorization ?? "").replace(/^Bearer\s+/i, ""));
|
|
167
|
+
const expected = Buffer.from(token);
|
|
168
|
+
return presented.length === expected.length && timingSafeEqual(presented, expected);
|
|
169
|
+
};
|
|
170
|
+
async function readJson(req, limit = 1024 * 1024) {
|
|
171
|
+
const chunks = [];
|
|
172
|
+
let size = 0;
|
|
173
|
+
for await (const c of req) {
|
|
174
|
+
size += c.length;
|
|
175
|
+
if (size > limit)
|
|
176
|
+
throw new Error("request body too large");
|
|
177
|
+
chunks.push(c);
|
|
178
|
+
}
|
|
179
|
+
return chunks.length ? JSON.parse(Buffer.concat(chunks).toString("utf8")) : undefined;
|
|
180
|
+
}
|
|
181
|
+
const sendJson = (res, status, body) => void res.writeHead(status, { "content-type": "application/json" }).end(JSON.stringify(body));
|
|
182
|
+
/** The board's sign-in endpoints: state, the scopes on offer, and starting or finishing a sign-in (never a token). */
|
|
183
|
+
async function handleAuth(req, res, path) {
|
|
184
|
+
if (!bearer(req, o.authKey))
|
|
185
|
+
return sendJson(res, 401, { error: "unauthorized" });
|
|
186
|
+
if (path === "/auth/status" && req.method === "GET")
|
|
187
|
+
return sendJson(res, 200, { configured: Boolean(o.upstream), ...auth.status() });
|
|
188
|
+
const flow = auth.signIn;
|
|
189
|
+
if (!flow)
|
|
190
|
+
return sendJson(res, 400, { error: `${o.name} needs no sign-in` });
|
|
191
|
+
if (!o.upstream)
|
|
192
|
+
return sendJson(res, 400, { error: notConnected() });
|
|
193
|
+
try {
|
|
194
|
+
if (path === "/auth/scopes" && req.method === "GET")
|
|
195
|
+
return sendJson(res, 200, await flow.scopes());
|
|
196
|
+
if (req.method !== "POST")
|
|
197
|
+
return sendJson(res, 405, { error: "method not allowed" });
|
|
198
|
+
if (path === "/auth/start") {
|
|
199
|
+
const { redirect_uri, scopes } = z.object({ redirect_uri: z.string().max(200), scopes: z.array(z.string().max(200)).max(200).optional() }).parse(await readJson(req));
|
|
200
|
+
return sendJson(res, 200, await flow.start(redirect_uri, scopes));
|
|
201
|
+
}
|
|
202
|
+
if (path === "/auth/finish") {
|
|
203
|
+
const { state, code } = z.object({ state: z.string().max(200), code: z.string().max(4096) }).parse(await readJson(req));
|
|
204
|
+
await flow.finish(state, code);
|
|
205
|
+
await reset(false).catch((err) => log.warn({ err: String(err).slice(0, 300) }, "connecting after sign-in failed"));
|
|
206
|
+
log.info({ scope: auth.status().scope }, `signed in to ${o.name}`);
|
|
207
|
+
return sendJson(res, 200, { ok: true });
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
catch (err) {
|
|
211
|
+
if (err instanceof SignInError || err instanceof z.ZodError)
|
|
212
|
+
return sendJson(res, 400, { error: err instanceof SignInError ? err.message : "bad request" });
|
|
213
|
+
throw err;
|
|
214
|
+
}
|
|
215
|
+
return sendJson(res, 404, { error: "not found" });
|
|
216
|
+
}
|
|
217
|
+
const http = createServer(async (req, res) => {
|
|
218
|
+
const url = new URL(req.url ?? "/", "http://localhost");
|
|
219
|
+
try {
|
|
220
|
+
if (url.pathname === "/healthz") {
|
|
221
|
+
const s = auth.status();
|
|
222
|
+
// Without a sign-in (a local server) the only question is whether it answers; a failed ping drops the client.
|
|
223
|
+
if (s.state === "none" && o.upstream) {
|
|
224
|
+
const down = await withUpstream((u) => u.client.ping({ timeout: 3000 })).then(() => undefined, (err) => { upstream = undefined; return `${o.name} didn't answer: ${String(err.message).slice(0, 150)}`; });
|
|
225
|
+
return sendJson(res, down ? 503 : 200, { ok: !down, state: s.state, ...(down ? { detail: down } : {}) });
|
|
226
|
+
}
|
|
227
|
+
const why = !o.upstream ? `${o.name} isn't set up` : s.state === "missing" ? `${o.name} not connected (Connect on the board)` : s.state === "expired" ? `${o.name} sign-in expired: ${s.detail ?? ""} (Reconnect on the board)` : hooks.health?.();
|
|
228
|
+
return sendJson(res, why ? 503 : 200, { ok: !why, state: s.state, ...(why ? { detail: why } : {}) });
|
|
229
|
+
}
|
|
230
|
+
if (url.pathname.startsWith("/auth/"))
|
|
231
|
+
return await handleAuth(req, res, url.pathname);
|
|
232
|
+
if (o.routes && (await o.routes(req, res)))
|
|
233
|
+
return;
|
|
234
|
+
const readOnly = url.pathname === "/mcp/read";
|
|
235
|
+
if (url.pathname !== "/mcp" && !(readOnly && o.readKey))
|
|
236
|
+
return void res.writeHead(404).end();
|
|
237
|
+
if (!bearer(req, readOnly ? o.readKey : o.serviceKey))
|
|
238
|
+
return void res.writeHead(401).end();
|
|
239
|
+
if (req.method !== "POST")
|
|
240
|
+
return void res.writeHead(405).end();
|
|
241
|
+
const body = await readJson(req, 8 * 1024 * 1024);
|
|
242
|
+
const msgs = (Array.isArray(body) ? body : [body]);
|
|
243
|
+
if (!readOnly && msgs.some((m) => m?.method === "tools/call")) {
|
|
244
|
+
try {
|
|
245
|
+
await o.caller(req);
|
|
246
|
+
}
|
|
247
|
+
catch (err) {
|
|
248
|
+
const reason = err.message;
|
|
249
|
+
log.warn({ reason }, "tool call refused");
|
|
250
|
+
const refused = (m) => ({ jsonrpc: "2.0", id: m?.id ?? null, result: refusal(`Refused: ${reason}.`) });
|
|
251
|
+
return sendJson(res, 200, Array.isArray(body) ? msgs.map(refused) : refused(msgs[0]));
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
const server = buildServer(readOnly);
|
|
255
|
+
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
|
|
256
|
+
res.on("close", () => {
|
|
257
|
+
void transport.close();
|
|
258
|
+
void server.close();
|
|
259
|
+
});
|
|
260
|
+
await server.connect(transport);
|
|
261
|
+
await transport.handleRequest(req, res, body);
|
|
262
|
+
}
|
|
263
|
+
catch (err) {
|
|
264
|
+
log.error({ err: err.message, path: url.pathname }, "request failed");
|
|
265
|
+
if (!res.headersSent)
|
|
266
|
+
res.writeHead(500).end();
|
|
267
|
+
}
|
|
268
|
+
});
|
|
269
|
+
return Object.assign(http, { call });
|
|
270
|
+
}
|