@indigoai/mcp-companion 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +48 -2
- package/dist/companion.js +232 -0
- package/dist/descriptors.js +13 -0
- package/dist/flavour.js +1 -0
- package/dist/flavours.js +16 -0
- package/dist/grants.js +65 -0
- package/dist/index.js +17 -0
- package/dist/keychain.js +10 -0
- package/dist/loopback.js +52 -0
- package/dist/oauth.js +88 -0
- package/dist/remote.js +23 -0
- package/dist/server.js +61 -0
- package/dist/state.js +18 -0
- package/package.json +32 -4
package/README.md
CHANGED
|
@@ -1,3 +1,49 @@
|
|
|
1
|
-
#
|
|
1
|
+
# indigo-mcp-companion
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The local MCP server that connects Claude to every indigo.ai environment a person works on. Sign-ins stay on the person's computer: refresh tokens in the system keychain, access tokens in memory, and no central service between Claude and a platform.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
Every release ships two builds from the same commit. The production one is for everyone. The staging one connects only staging environments and is for the staff. Always install an exact version: `X.Y.Z` below is the release tag without its `v`.
|
|
8
|
+
|
|
9
|
+
| | Production | Staging |
|
|
10
|
+
|---|---|---|
|
|
11
|
+
| npm package | `@indigoai/mcp-companion` | `@indigoai/mcp-companion-staging` |
|
|
12
|
+
| Claude Desktop bundle | `indigo-mcp-companion.mcpb` | `indigo-mcp-companion-staging.mcpb` |
|
|
13
|
+
| Directory | `https://mcp.indigo.ai` | `https://staging.mcp.indigo.ai` |
|
|
14
|
+
|
|
15
|
+
- **Claude Desktop:** download the bundle from the `mcpb` job of the release tag's pipeline (`mcpb: [production]` or `mcpb: [staging]`), then open it. The two builds install side by side.
|
|
16
|
+
- **Claude Code:** `claude mcp add indigo -- npx -y @indigoai/mcp-companion@X.Y.Z` (on Windows: `claude mcp add indigo -- cmd /c npx -y @indigoai/mcp-companion@X.Y.Z`). For staging: `claude mcp add indigo-staging -- npx -y @indigoai/mcp-companion-staging@X.Y.Z`.
|
|
17
|
+
- **Codex:** in `~/.codex/config.toml`
|
|
18
|
+
|
|
19
|
+
```toml
|
|
20
|
+
[mcp_servers.indigo]
|
|
21
|
+
command = "npx"
|
|
22
|
+
args = ["-y", "@indigoai/mcp-companion@X.Y.Z"]
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## How it works
|
|
26
|
+
|
|
27
|
+
1. `list_environments` opens the browser on the directory's email step the first time (or with `add_email`). The directory answers with descriptors of the person's environments, signed by DevOps. The companion verifies each one with the public key its build carries (`src/flavours.ts`): while a build's key is empty, every descriptor is refused.
|
|
28
|
+
2. `connect_environment` checks that the platform's published metadata matches the descriptor, then signs in on that platform in the browser (PKCE, loopback redirect). It refuses a descriptor that has expired.
|
|
29
|
+
3. `list_workspaces`, `describe_tools`, `run_read_tool` and `run_write_tool` name their environment on every call, and every result, errors included, starts with that `environment_id` (argument-validation errors aside). Read and write are told apart by the platform tools' `readOnlyHint`.
|
|
30
|
+
4. A connected environment keeps working on the descriptor it was connected with, even once that expires or while the directory is down. The next email verification updates it.
|
|
31
|
+
5. `disconnect_environment` revokes the grant on the platform before forgetting it locally.
|
|
32
|
+
|
|
33
|
+
State lives in `~/.indigo-mcp-companion/` (`~/.indigo-mcp-companion-staging/` for the staging build) and holds no secrets. `INDIGO_DIRECTORY_URL` points a build at another directory, for development.
|
|
34
|
+
|
|
35
|
+
## Develop
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
npm ci
|
|
39
|
+
npm test # unit and end-to-end tests against fake directory and platforms
|
|
40
|
+
KEYCHAIN_SMOKE=1 npm test # also round-trips a secret through the real system keychain
|
|
41
|
+
npm run build
|
|
42
|
+
./scripts/pack-mcpb.sh # build/indigo-mcp-companion.mcpb
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Release
|
|
46
|
+
|
|
47
|
+
1. Push a tag `vX.Y.Z`. The pipeline writes that version into the package and the bundle.
|
|
48
|
+
2. Start the `mcpb` and `npm` jobs by hand in the tag's pipeline. Each runs once for production and once for staging.
|
|
49
|
+
3. The `mcpb` job fails unless the `MCPB_SIGNING_CERT` and `MCPB_SIGNING_KEY` file variables are set (plus `MCPB_SIGNING_INTERMEDIATE` when the chain needs one). Publishing needs an `NPM_TOKEN` allowed to publish both packages. Protect the `v*` tags and mark these variables protected (and `NPM_TOKEN` masked): protected variables only reach pipelines on protected tags, and an unprotected signing key is readable from any branch's pipeline. Packages are published without npm provenance, which needs a public source repository.
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { decodeJwt } from "jose";
|
|
4
|
+
import { verifyDescriptor } from "./descriptors.js";
|
|
5
|
+
import { grantAccount, Grants, NeedsReconnect } from "./grants.js";
|
|
6
|
+
import { startLoopback } from "./loopback.js";
|
|
7
|
+
import { authorizeUrl, checkPlatformMetadata, exchangeDirectoryCode, exchangePlatformCode, HttpError, OAuthError, revokePlatformToken, } from "./oauth.js";
|
|
8
|
+
import { withRemote } from "./remote.js";
|
|
9
|
+
import { loadState, saveState } from "./state.js";
|
|
10
|
+
const EMAIL_PROOF = "directory-email-proof";
|
|
11
|
+
function reachable(d, error) {
|
|
12
|
+
if (error.message !== "fetch failed")
|
|
13
|
+
return error;
|
|
14
|
+
if (error.cause?.message === "unexpected redirect") {
|
|
15
|
+
return new Error(`${d.label} answered with a redirect, which is never followed with a sign-in`);
|
|
16
|
+
}
|
|
17
|
+
return new Error(`${d.label} could not be reached (${new URL(d.mcp_resource).host}): check the network or VPN`);
|
|
18
|
+
}
|
|
19
|
+
const moved = (d, c) => c.issuer !== d.issuer || c.resource !== d.mcp_resource;
|
|
20
|
+
export class Companion {
|
|
21
|
+
opts;
|
|
22
|
+
grants;
|
|
23
|
+
notice = null;
|
|
24
|
+
discovering = null;
|
|
25
|
+
constructor(opts) {
|
|
26
|
+
this.opts = opts;
|
|
27
|
+
this.grants = new Grants(opts.keychain, join(opts.dir, "locks"));
|
|
28
|
+
}
|
|
29
|
+
async listEnvironments(addEmail = false) {
|
|
30
|
+
const state = loadState(this.opts.dir);
|
|
31
|
+
const environments = this.descriptors().map((d) => ({
|
|
32
|
+
environment_id: d.environment_id,
|
|
33
|
+
label: d.label,
|
|
34
|
+
status: state.connections[d.environment_id]?.status ?? "not connected",
|
|
35
|
+
}));
|
|
36
|
+
const notice = this.notice;
|
|
37
|
+
this.notice = null;
|
|
38
|
+
if (addEmail || (environments.length === 0 && !notice)) {
|
|
39
|
+
if (this.discovering && !addEmail) {
|
|
40
|
+
return "Still waiting for the email verification in the browser. Finish there, then call list_environments again.";
|
|
41
|
+
}
|
|
42
|
+
return (await this.discover()).message;
|
|
43
|
+
}
|
|
44
|
+
return JSON.stringify({ environments, emails: state.emails, ...(notice ? { notice } : {}) }, null, 2);
|
|
45
|
+
}
|
|
46
|
+
async discover() {
|
|
47
|
+
const loopback = await startLoopback(this.opts.directoryUrl);
|
|
48
|
+
const done = loopback.code
|
|
49
|
+
.then(async (code) => {
|
|
50
|
+
const answer = await exchangeDirectoryCode(this.opts.directoryUrl, code, loopback.verifier, loopback.redirectUri, this.opts.keychain.get(EMAIL_PROOF));
|
|
51
|
+
const state = loadState(this.opts.dir);
|
|
52
|
+
let refused = 0;
|
|
53
|
+
for (const jws of answer.descriptors) {
|
|
54
|
+
try {
|
|
55
|
+
const seen = Object.fromEntries(Object.values(state.descriptors).map((x) => [x.environment_id, x.version]));
|
|
56
|
+
const d = await verifyDescriptor(jws, this.opts.descriptorKey, seen);
|
|
57
|
+
state.descriptors[d.environment_id] = d;
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
refused++;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
state.emails = answer.emails;
|
|
64
|
+
saveState(this.opts.dir, state);
|
|
65
|
+
this.opts.keychain.set(EMAIL_PROOF, answer.email_proof);
|
|
66
|
+
if (refused > 0)
|
|
67
|
+
this.notice = `${refused} environment descriptor(s) failed verification and were ignored`;
|
|
68
|
+
else if (Object.keys(state.descriptors).length === 0)
|
|
69
|
+
this.notice = "no environment is available for your email";
|
|
70
|
+
})
|
|
71
|
+
.catch((error) => {
|
|
72
|
+
this.notice = `email verification failed: ${error.message}`;
|
|
73
|
+
});
|
|
74
|
+
this.discovering = done.finally(() => {
|
|
75
|
+
this.discovering = null;
|
|
76
|
+
});
|
|
77
|
+
await this.opts.openBrowser(authorizeUrl(`${this.opts.directoryUrl}/authorize`, {
|
|
78
|
+
redirect_uri: loopback.redirectUri,
|
|
79
|
+
code_challenge: loopback.challenge,
|
|
80
|
+
state: loopback.state,
|
|
81
|
+
}));
|
|
82
|
+
return {
|
|
83
|
+
message: "A browser tab is open to verify your email. Follow the link we send you, then call list_environments again.",
|
|
84
|
+
done,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
async connect(environmentId) {
|
|
88
|
+
const d = this.descriptor(environmentId);
|
|
89
|
+
if (d.exp <= Date.now() / 1000) {
|
|
90
|
+
throw new Error(`${d.label}'s details expired: call list_environments with add_email to verify your email again`);
|
|
91
|
+
}
|
|
92
|
+
if (loadState(this.opts.dir).connections[environmentId]?.status === "connected") {
|
|
93
|
+
throw new Error(`${d.label} is already connected. Disconnect it first to sign in with another account.`);
|
|
94
|
+
}
|
|
95
|
+
await checkPlatformMetadata(d).catch((error) => {
|
|
96
|
+
throw reachable(d, error);
|
|
97
|
+
});
|
|
98
|
+
const loopback = await startLoopback(d.issuer);
|
|
99
|
+
const done = loopback.code
|
|
100
|
+
.then(async (code) => {
|
|
101
|
+
const tokens = await exchangePlatformCode(d, code, loopback.verifier, loopback.redirectUri);
|
|
102
|
+
const connection = {
|
|
103
|
+
issuer: d.issuer,
|
|
104
|
+
resource: d.mcp_resource,
|
|
105
|
+
sub: String(decodeJwt(tokens.access_token).sub),
|
|
106
|
+
grantId: randomUUID(),
|
|
107
|
+
status: "connected",
|
|
108
|
+
};
|
|
109
|
+
this.grants.store(connection, tokens);
|
|
110
|
+
const state = loadState(this.opts.dir);
|
|
111
|
+
state.connections[environmentId] = connection;
|
|
112
|
+
saveState(this.opts.dir, state);
|
|
113
|
+
})
|
|
114
|
+
.catch((error) => {
|
|
115
|
+
this.notice = `connecting ${d.label} failed: ${error.message}`;
|
|
116
|
+
});
|
|
117
|
+
await this.opts.openBrowser(authorizeUrl(d.authorization_endpoint, {
|
|
118
|
+
redirect_uri: loopback.redirectUri,
|
|
119
|
+
code_challenge: loopback.challenge,
|
|
120
|
+
state: loopback.state,
|
|
121
|
+
resource: d.mcp_resource,
|
|
122
|
+
}));
|
|
123
|
+
return {
|
|
124
|
+
message: `A browser tab is open to sign in to ${d.label}. Finish there, then call list_environments to check it is connected.`,
|
|
125
|
+
done,
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
async disconnect(environmentId) {
|
|
129
|
+
const { descriptors, connections } = loadState(this.opts.dir);
|
|
130
|
+
const d = descriptors[environmentId] ?? this.descriptor(environmentId);
|
|
131
|
+
const connection = connections[environmentId];
|
|
132
|
+
if (!connection)
|
|
133
|
+
throw new Error(`${d.label} is not connected`);
|
|
134
|
+
const relocated = moved(d, connection);
|
|
135
|
+
let revoked = false;
|
|
136
|
+
if (relocated) {
|
|
137
|
+
this.grants.forget(connection);
|
|
138
|
+
}
|
|
139
|
+
else if (connection.status === "connected") {
|
|
140
|
+
revoked = await this.grants.withLock(connection, async () => {
|
|
141
|
+
const refreshToken = this.opts.keychain.get(grantAccount(connection));
|
|
142
|
+
if (!refreshToken)
|
|
143
|
+
return false;
|
|
144
|
+
try {
|
|
145
|
+
await revokePlatformToken(d, refreshToken);
|
|
146
|
+
}
|
|
147
|
+
catch (error) {
|
|
148
|
+
if (error instanceof HttpError && error.status < 500) {
|
|
149
|
+
const code = error instanceof OAuthError ? ` ${error.code}` : "";
|
|
150
|
+
throw new Error(`Revocation refused: ${d.label} answered HTTP ${error.status}${code}, so it is still connected.`);
|
|
151
|
+
}
|
|
152
|
+
throw new Error(`Revocation pending: ${d.label} could not be reached, so it is still connected. Try again later.`);
|
|
153
|
+
}
|
|
154
|
+
this.grants.forget(connection);
|
|
155
|
+
return true;
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
const state = loadState(this.opts.dir);
|
|
159
|
+
delete state.connections[environmentId];
|
|
160
|
+
saveState(this.opts.dir, state);
|
|
161
|
+
if (relocated) {
|
|
162
|
+
return `${d.label} is disconnected on this computer. It moved to another address, so its old sign-in could not be revoked: it lapses there after 30 days without use.`;
|
|
163
|
+
}
|
|
164
|
+
return revoked
|
|
165
|
+
? `${d.label} is disconnected and its sign-in revoked.`
|
|
166
|
+
: `${d.label} is disconnected on this computer. No stored sign-in was left to revoke.`;
|
|
167
|
+
}
|
|
168
|
+
async listWorkspaces(environmentId) {
|
|
169
|
+
return this.call(this.descriptor(environmentId), (client) => client.callTool({ name: "list_workspaces", arguments: {} }));
|
|
170
|
+
}
|
|
171
|
+
async describeTools(environmentId) {
|
|
172
|
+
const d = this.descriptor(environmentId);
|
|
173
|
+
const tools = await this.call(d, async (client) => (await client.listTools()).tools);
|
|
174
|
+
return JSON.stringify(tools.map((t) => ({
|
|
175
|
+
name: t.name,
|
|
176
|
+
access: t.annotations?.readOnlyHint === true ? "read" : "write",
|
|
177
|
+
description: t.description,
|
|
178
|
+
inputSchema: t.inputSchema,
|
|
179
|
+
})), null, 2);
|
|
180
|
+
}
|
|
181
|
+
async runTool(environmentId, tool, args, access) {
|
|
182
|
+
const d = this.descriptor(environmentId);
|
|
183
|
+
return this.call(d, async (client) => {
|
|
184
|
+
const found = (await client.listTools()).tools.find((t) => t.name === tool);
|
|
185
|
+
if (!found)
|
|
186
|
+
throw new Error(`${d.label} has no tool named ${tool}`);
|
|
187
|
+
const isRead = found.annotations?.readOnlyHint === true;
|
|
188
|
+
if (access === "read" && !isRead)
|
|
189
|
+
throw new Error(`${tool} changes data: use run_write_tool`);
|
|
190
|
+
if (access === "write" && isRead)
|
|
191
|
+
throw new Error(`${tool} only reads: use run_read_tool`);
|
|
192
|
+
return client.callTool({ name: tool, arguments: args });
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
async call(d, fn) {
|
|
196
|
+
const connection = loadState(this.opts.dir).connections[d.environment_id];
|
|
197
|
+
if (connection?.status !== "connected") {
|
|
198
|
+
throw new Error(`${d.label} is not connected: call connect_environment first`);
|
|
199
|
+
}
|
|
200
|
+
if (moved(d, connection)) {
|
|
201
|
+
throw new Error(`${d.label} moved to another address: disconnect it, then connect it again`);
|
|
202
|
+
}
|
|
203
|
+
try {
|
|
204
|
+
const result = await withRemote(d.mcp_resource, (force) => this.grants.accessToken(d, connection, force), fn);
|
|
205
|
+
const environment = result?._meta?.environment;
|
|
206
|
+
if (environment !== undefined && environment !== d.issuer) {
|
|
207
|
+
throw new Error(`the answer came from ${String(environment)}, not from ${d.label}`);
|
|
208
|
+
}
|
|
209
|
+
return result;
|
|
210
|
+
}
|
|
211
|
+
catch (error) {
|
|
212
|
+
if (error instanceof NeedsReconnect) {
|
|
213
|
+
const state = loadState(this.opts.dir);
|
|
214
|
+
state.connections[d.environment_id] = { ...connection, status: "reconnect" };
|
|
215
|
+
saveState(this.opts.dir, state);
|
|
216
|
+
throw new Error(`${d.label} needs to be connected again: call connect_environment`);
|
|
217
|
+
}
|
|
218
|
+
throw reachable(d, error);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
descriptors() {
|
|
222
|
+
const { descriptors, connections } = loadState(this.opts.dir);
|
|
223
|
+
const now = Date.now() / 1000;
|
|
224
|
+
return Object.values(descriptors).filter((d) => d.exp > now || connections[d.environment_id]);
|
|
225
|
+
}
|
|
226
|
+
descriptor(environmentId) {
|
|
227
|
+
const d = this.descriptors().find((x) => x.environment_id === environmentId);
|
|
228
|
+
if (!d)
|
|
229
|
+
throw new Error(`unknown environment: ${environmentId}. Call list_environments to see yours.`);
|
|
230
|
+
return d;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { compactVerify, importSPKI } from "jose";
|
|
2
|
+
export async function verifyDescriptor(jws, publicKeyPem, seenVersions) {
|
|
3
|
+
const key = await importSPKI(publicKeyPem, "ES256");
|
|
4
|
+
const { payload } = await compactVerify(jws, key, { algorithms: ["ES256"] });
|
|
5
|
+
const claims = JSON.parse(new TextDecoder().decode(payload));
|
|
6
|
+
if (!Number.isInteger(claims.version) || !Number.isInteger(claims.exp))
|
|
7
|
+
throw new Error("descriptor without version or exp");
|
|
8
|
+
if (claims.exp <= Date.now() / 1000)
|
|
9
|
+
throw new Error("descriptor expired");
|
|
10
|
+
if (claims.version < (seenVersions[claims.environment_id] ?? 0))
|
|
11
|
+
throw new Error("descriptor older than one already seen");
|
|
12
|
+
return claims;
|
|
13
|
+
}
|
package/dist/flavour.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { production as default } from "./flavours.js";
|
package/dist/flavours.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// The companion's trust anchor is the public half of DevOps' offline descriptor key, so each build
|
|
2
|
+
// carries its own and picks it when the package is built, never at runtime. An empty key refuses
|
|
3
|
+
// every descriptor.
|
|
4
|
+
export const production = {
|
|
5
|
+
name: "indigo-mcp-companion",
|
|
6
|
+
directoryUrl: "https://mcp.indigo.ai",
|
|
7
|
+
descriptorKey: "",
|
|
8
|
+
};
|
|
9
|
+
export const staging = {
|
|
10
|
+
name: "indigo-mcp-companion-staging",
|
|
11
|
+
directoryUrl: "https://staging.mcp.indigo.ai",
|
|
12
|
+
descriptorKey: `-----BEGIN PUBLIC KEY-----
|
|
13
|
+
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAErTrHYZIy4yR4Fz+4Zzcp6wa8CfL/
|
|
14
|
+
c53P7uRovYU6g2oUWcCMYSydZNArJINi0TLgQ5VGiVJR87HXrRf0L1EI7A==
|
|
15
|
+
-----END PUBLIC KEY-----`,
|
|
16
|
+
};
|
package/dist/grants.js
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import lockfile from "proper-lockfile";
|
|
5
|
+
import { OAuthError, refreshPlatformToken } from "./oauth.js";
|
|
6
|
+
export class NeedsReconnect extends Error {
|
|
7
|
+
}
|
|
8
|
+
export function grantAccount(c) {
|
|
9
|
+
return JSON.stringify([c.issuer, c.resource, c.sub, c.grantId]);
|
|
10
|
+
}
|
|
11
|
+
export class Grants {
|
|
12
|
+
keychain;
|
|
13
|
+
lockDir;
|
|
14
|
+
access = new Map();
|
|
15
|
+
constructor(keychain, lockDir) {
|
|
16
|
+
this.keychain = keychain;
|
|
17
|
+
this.lockDir = lockDir;
|
|
18
|
+
}
|
|
19
|
+
store(c, tokens) {
|
|
20
|
+
this.keychain.set(grantAccount(c), tokens.refresh_token);
|
|
21
|
+
this.access.set(grantAccount(c), { token: tokens.access_token, expiresAt: Date.now() + tokens.expires_in * 1000 });
|
|
22
|
+
}
|
|
23
|
+
forget(c) {
|
|
24
|
+
this.keychain.delete(grantAccount(c));
|
|
25
|
+
this.access.delete(grantAccount(c));
|
|
26
|
+
}
|
|
27
|
+
async accessToken(d, c, force = false) {
|
|
28
|
+
const cached = this.access.get(grantAccount(c));
|
|
29
|
+
if (!force && cached && cached.expiresAt - 30_000 > Date.now())
|
|
30
|
+
return cached.token;
|
|
31
|
+
return this.withLock(c, async () => {
|
|
32
|
+
const refreshToken = this.keychain.get(grantAccount(c));
|
|
33
|
+
if (!refreshToken)
|
|
34
|
+
throw new NeedsReconnect();
|
|
35
|
+
let tokens;
|
|
36
|
+
try {
|
|
37
|
+
tokens = await refreshPlatformToken(d, refreshToken);
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
if (!(error instanceof OAuthError) || error.code !== "invalid_grant")
|
|
41
|
+
throw error;
|
|
42
|
+
this.forget(c);
|
|
43
|
+
throw new NeedsReconnect();
|
|
44
|
+
}
|
|
45
|
+
this.store(c, tokens);
|
|
46
|
+
return tokens.access_token;
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
async withLock(c, fn) {
|
|
50
|
+
mkdirSync(this.lockDir, { recursive: true });
|
|
51
|
+
const file = join(this.lockDir, createHash("sha256").update(grantAccount(c)).digest("hex"));
|
|
52
|
+
writeFileSync(file, "", { flag: "a" });
|
|
53
|
+
const release = await lockfile.lock(file, {
|
|
54
|
+
stale: 30_000,
|
|
55
|
+
retries: { retries: 100, minTimeout: 50, maxTimeout: 500 },
|
|
56
|
+
onCompromised: () => { },
|
|
57
|
+
});
|
|
58
|
+
try {
|
|
59
|
+
return await fn();
|
|
60
|
+
}
|
|
61
|
+
finally {
|
|
62
|
+
await release();
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
5
|
+
import open from "open";
|
|
6
|
+
import { Companion } from "./companion.js";
|
|
7
|
+
import flavour from "./flavour.js";
|
|
8
|
+
import { systemKeychain } from "./keychain.js";
|
|
9
|
+
import { buildServer } from "./server.js";
|
|
10
|
+
const companion = new Companion({
|
|
11
|
+
directoryUrl: process.env.INDIGO_DIRECTORY_URL ?? flavour.directoryUrl,
|
|
12
|
+
descriptorKey: flavour.descriptorKey,
|
|
13
|
+
keychain: systemKeychain,
|
|
14
|
+
dir: join(homedir(), `.${flavour.name}`),
|
|
15
|
+
openBrowser: (url) => open(url),
|
|
16
|
+
});
|
|
17
|
+
await buildServer(companion).connect(new StdioServerTransport());
|
package/dist/keychain.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { Entry } from "@napi-rs/keyring";
|
|
2
|
+
import flavour from "./flavour.js";
|
|
3
|
+
const SERVICE = flavour.name;
|
|
4
|
+
export const systemKeychain = {
|
|
5
|
+
get: (account) => new Entry(SERVICE, account).getPassword(),
|
|
6
|
+
set: (account, secret) => new Entry(SERVICE, account).setPassword(secret),
|
|
7
|
+
delete: (account) => {
|
|
8
|
+
new Entry(SERVICE, account).deletePassword();
|
|
9
|
+
},
|
|
10
|
+
};
|
package/dist/loopback.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
+
import { createServer } from "node:http";
|
|
3
|
+
export async function startLoopback(issuer, timeoutMs = 600_000) {
|
|
4
|
+
const verifier = randomBytes(32).toString("base64url");
|
|
5
|
+
const state = randomBytes(16).toString("base64url");
|
|
6
|
+
let resolve;
|
|
7
|
+
let reject;
|
|
8
|
+
const params = new Promise((res, rej) => {
|
|
9
|
+
resolve = res;
|
|
10
|
+
reject = rej;
|
|
11
|
+
});
|
|
12
|
+
const server = createServer((req, res) => {
|
|
13
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
14
|
+
if (url.pathname !== "/callback") {
|
|
15
|
+
res.writeHead(404).end();
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
|
|
19
|
+
res.end("<p>Done. You can close this tab and go back to Claude.</p>");
|
|
20
|
+
finish();
|
|
21
|
+
resolve(url.searchParams);
|
|
22
|
+
});
|
|
23
|
+
const timer = setTimeout(() => {
|
|
24
|
+
finish();
|
|
25
|
+
reject(new Error("the sign-in in the browser timed out"));
|
|
26
|
+
}, timeoutMs);
|
|
27
|
+
const finish = () => {
|
|
28
|
+
clearTimeout(timer);
|
|
29
|
+
server.close();
|
|
30
|
+
};
|
|
31
|
+
await new Promise((res) => server.listen(0, "127.0.0.1", res));
|
|
32
|
+
const code = params.then((p) => {
|
|
33
|
+
if (p.get("state") !== state)
|
|
34
|
+
throw new Error("the sign-in came back with the wrong state");
|
|
35
|
+
if (p.get("iss") !== issuer)
|
|
36
|
+
throw new Error("the sign-in came back from the wrong issuer");
|
|
37
|
+
const error = p.get("error");
|
|
38
|
+
if (error)
|
|
39
|
+
throw new Error(`the sign-in was refused: ${error}`);
|
|
40
|
+
const value = p.get("code");
|
|
41
|
+
if (!value)
|
|
42
|
+
throw new Error("the sign-in came back without a code");
|
|
43
|
+
return value;
|
|
44
|
+
});
|
|
45
|
+
return {
|
|
46
|
+
redirectUri: `http://127.0.0.1:${server.address().port}/callback`,
|
|
47
|
+
verifier,
|
|
48
|
+
challenge: createHash("sha256").update(verifier).digest("base64url"),
|
|
49
|
+
state,
|
|
50
|
+
code,
|
|
51
|
+
};
|
|
52
|
+
}
|
package/dist/oauth.js
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
export const CLIENT_ID = "https://mcp.indigo.ai/companion/client-metadata.json";
|
|
2
|
+
export class HttpError extends Error {
|
|
3
|
+
status;
|
|
4
|
+
constructor(status, message) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.status = status;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
export class OAuthError extends HttpError {
|
|
10
|
+
code;
|
|
11
|
+
constructor(status, code) {
|
|
12
|
+
super(status, `the platform answered ${code}`);
|
|
13
|
+
this.code = code;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
async function postForm(url, params) {
|
|
17
|
+
const res = await fetch(url, {
|
|
18
|
+
method: "POST",
|
|
19
|
+
headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
|
|
20
|
+
body: new URLSearchParams(params),
|
|
21
|
+
redirect: "error",
|
|
22
|
+
});
|
|
23
|
+
const body = await res.json().catch(() => ({}));
|
|
24
|
+
if (!res.ok) {
|
|
25
|
+
if ((res.status === 400 || res.status === 401) && typeof body.error === "string")
|
|
26
|
+
throw new OAuthError(res.status, body.error);
|
|
27
|
+
throw new HttpError(res.status, `${new URL(url).host} answered HTTP ${res.status}`);
|
|
28
|
+
}
|
|
29
|
+
return body;
|
|
30
|
+
}
|
|
31
|
+
export function authorizeUrl(endpoint, params) {
|
|
32
|
+
const url = new URL(endpoint);
|
|
33
|
+
for (const [name, value] of Object.entries({ response_type: "code", client_id: CLIENT_ID, code_challenge_method: "S256", ...params })) {
|
|
34
|
+
url.searchParams.set(name, value);
|
|
35
|
+
}
|
|
36
|
+
return url.toString();
|
|
37
|
+
}
|
|
38
|
+
export function exchangeDirectoryCode(directoryUrl, code, verifier, redirectUri, emailProof) {
|
|
39
|
+
return postForm(`${directoryUrl}/token`, {
|
|
40
|
+
grant_type: "authorization_code",
|
|
41
|
+
code,
|
|
42
|
+
code_verifier: verifier,
|
|
43
|
+
client_id: CLIENT_ID,
|
|
44
|
+
redirect_uri: redirectUri,
|
|
45
|
+
...(emailProof ? { email_proof: emailProof } : {}),
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
async function getJson(url) {
|
|
49
|
+
const res = await fetch(url, { headers: { accept: "application/json" }, redirect: "error" });
|
|
50
|
+
if (!res.ok)
|
|
51
|
+
throw new Error(`${url} answered ${res.status}`);
|
|
52
|
+
return res.json();
|
|
53
|
+
}
|
|
54
|
+
export async function checkPlatformMetadata(d) {
|
|
55
|
+
const resource = new URL(d.mcp_resource);
|
|
56
|
+
const prm = await getJson(`${resource.origin}/.well-known/oauth-protected-resource${resource.pathname}`);
|
|
57
|
+
const as = await getJson(`${d.issuer}/.well-known/oauth-authorization-server`);
|
|
58
|
+
const matches = prm.resource === d.mcp_resource &&
|
|
59
|
+
Array.isArray(prm.authorization_servers) &&
|
|
60
|
+
prm.authorization_servers.includes(d.issuer) &&
|
|
61
|
+
as.issuer === d.issuer &&
|
|
62
|
+
as.authorization_endpoint === d.authorization_endpoint &&
|
|
63
|
+
as.token_endpoint === d.token_endpoint &&
|
|
64
|
+
as.revocation_endpoint === d.revocation_endpoint;
|
|
65
|
+
if (!matches)
|
|
66
|
+
throw new Error(`${d.label} publishes metadata that does not match its signed descriptor`);
|
|
67
|
+
}
|
|
68
|
+
export function exchangePlatformCode(d, code, verifier, redirectUri) {
|
|
69
|
+
return postForm(d.token_endpoint, {
|
|
70
|
+
grant_type: "authorization_code",
|
|
71
|
+
code,
|
|
72
|
+
code_verifier: verifier,
|
|
73
|
+
client_id: CLIENT_ID,
|
|
74
|
+
redirect_uri: redirectUri,
|
|
75
|
+
resource: d.mcp_resource,
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
export function refreshPlatformToken(d, refreshToken) {
|
|
79
|
+
return postForm(d.token_endpoint, {
|
|
80
|
+
grant_type: "refresh_token",
|
|
81
|
+
refresh_token: refreshToken,
|
|
82
|
+
client_id: CLIENT_ID,
|
|
83
|
+
resource: d.mcp_resource,
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
export async function revokePlatformToken(d, refreshToken) {
|
|
87
|
+
await postForm(d.revocation_endpoint, { token: refreshToken, client_id: CLIENT_ID });
|
|
88
|
+
}
|
package/dist/remote.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
2
|
+
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
3
|
+
export async function withRemote(resource, token, fn) {
|
|
4
|
+
const authFetch = async (url, init) => {
|
|
5
|
+
const send = async (force) => {
|
|
6
|
+
const headers = new Headers(init?.headers);
|
|
7
|
+
headers.set("authorization", `Bearer ${await token(force)}`);
|
|
8
|
+
return fetch(url, { ...init, headers, redirect: "error" });
|
|
9
|
+
};
|
|
10
|
+
const res = await send(false);
|
|
11
|
+
return res.status === 401 ? send(true) : res;
|
|
12
|
+
};
|
|
13
|
+
const client = new Client({ name: "indigo-mcp-companion", version: "0.1.0" });
|
|
14
|
+
const transport = new StreamableHTTPClientTransport(new URL(resource), { fetch: authFetch });
|
|
15
|
+
await client.connect(transport);
|
|
16
|
+
try {
|
|
17
|
+
return await fn(client);
|
|
18
|
+
}
|
|
19
|
+
finally {
|
|
20
|
+
await transport.terminateSession().catch(() => { });
|
|
21
|
+
await client.close();
|
|
22
|
+
}
|
|
23
|
+
}
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
const text = (value) => ({ content: [{ type: "text", text: value }] });
|
|
4
|
+
const environmentId = z
|
|
5
|
+
.string({ required_error: "environment_id is required: call list_environments to see yours" })
|
|
6
|
+
.describe("The environment's id, as list_environments returns it");
|
|
7
|
+
async function inEnvironment(environment_id, run) {
|
|
8
|
+
const stamp = { type: "text", text: `environment_id: ${environment_id}` };
|
|
9
|
+
try {
|
|
10
|
+
const result = await run();
|
|
11
|
+
const { content, ...rest } = typeof result === "string" ? text(result) : result;
|
|
12
|
+
return { ...rest, content: [stamp, ...content] };
|
|
13
|
+
}
|
|
14
|
+
catch (error) {
|
|
15
|
+
return { isError: true, content: [stamp, { type: "text", text: error.message }] };
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export function buildServer(companion) {
|
|
19
|
+
const server = new McpServer({ name: "indigo-mcp-companion", version: "0.1.0" });
|
|
20
|
+
server.registerTool("list_environments", {
|
|
21
|
+
description: "List the indigo.ai environments you can connect, each with its status. The first time, or with add_email, it opens the browser to verify an email address: finish there, then call this again.",
|
|
22
|
+
inputSchema: { add_email: z.boolean().optional().describe("Verify one more email address, for example a client's domain") },
|
|
23
|
+
annotations: { destructiveHint: false },
|
|
24
|
+
}, async ({ add_email }) => text(await companion.listEnvironments(add_email)));
|
|
25
|
+
server.registerTool("connect_environment", {
|
|
26
|
+
description: "Connect one environment: opens its sign-in page in the browser. Finish there, then call list_environments to check.",
|
|
27
|
+
inputSchema: { environment_id: environmentId },
|
|
28
|
+
annotations: { destructiveHint: false },
|
|
29
|
+
}, ({ environment_id }) => inEnvironment(environment_id, async () => (await companion.connect(environment_id)).message));
|
|
30
|
+
server.registerTool("disconnect_environment", {
|
|
31
|
+
description: "Revoke this environment's sign-in on the platform, then forget it on this computer.",
|
|
32
|
+
inputSchema: { environment_id: environmentId },
|
|
33
|
+
annotations: { destructiveHint: true },
|
|
34
|
+
}, ({ environment_id }) => inEnvironment(environment_id, () => companion.disconnect(environment_id)));
|
|
35
|
+
server.registerTool("list_workspaces", {
|
|
36
|
+
description: "List the workspaces of one connected environment.",
|
|
37
|
+
inputSchema: { environment_id: environmentId },
|
|
38
|
+
annotations: { readOnlyHint: true },
|
|
39
|
+
}, ({ environment_id }) => inEnvironment(environment_id, () => companion.listWorkspaces(environment_id)));
|
|
40
|
+
server.registerTool("describe_tools", {
|
|
41
|
+
description: "List the platform tools of one environment, read live, each marked read or write. Call them with run_read_tool or run_write_tool.",
|
|
42
|
+
inputSchema: { environment_id: environmentId },
|
|
43
|
+
annotations: { readOnlyHint: true },
|
|
44
|
+
}, ({ environment_id }) => inEnvironment(environment_id, () => companion.describeTools(environment_id)));
|
|
45
|
+
const runInput = {
|
|
46
|
+
environment_id: environmentId,
|
|
47
|
+
tool: z.string().describe("A tool name from describe_tools"),
|
|
48
|
+
arguments: z.record(z.unknown()).default({}).describe("The tool's arguments"),
|
|
49
|
+
};
|
|
50
|
+
server.registerTool("run_read_tool", {
|
|
51
|
+
description: "Run a platform tool that only reads, on the named environment. Refuses tools that change data.",
|
|
52
|
+
inputSchema: runInput,
|
|
53
|
+
annotations: { readOnlyHint: true },
|
|
54
|
+
}, ({ environment_id, tool, arguments: args }) => inEnvironment(environment_id, () => companion.runTool(environment_id, tool, args, "read")));
|
|
55
|
+
server.registerTool("run_write_tool", {
|
|
56
|
+
description: "Run a platform tool that changes data, on the named environment. Always ask the user to confirm first, stating the environment, the workspace and the action.",
|
|
57
|
+
inputSchema: runInput,
|
|
58
|
+
annotations: { readOnlyHint: false, destructiveHint: true },
|
|
59
|
+
}, ({ environment_id, tool, arguments: args }) => inEnvironment(environment_id, () => companion.runTool(environment_id, tool, args, "write")));
|
|
60
|
+
return server;
|
|
61
|
+
}
|
package/dist/state.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
export function loadState(dir) {
|
|
4
|
+
try {
|
|
5
|
+
return JSON.parse(readFileSync(join(dir, "state.json"), "utf8"));
|
|
6
|
+
}
|
|
7
|
+
catch (error) {
|
|
8
|
+
if (error.code !== "ENOENT")
|
|
9
|
+
throw error;
|
|
10
|
+
return { descriptors: {}, emails: [], connections: {} };
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
export function saveState(dir, state) {
|
|
14
|
+
mkdirSync(dir, { recursive: true });
|
|
15
|
+
const tmp = join(dir, `state.json.${process.pid}`);
|
|
16
|
+
writeFileSync(tmp, JSON.stringify(state, null, 2));
|
|
17
|
+
renameSync(tmp, join(dir, "state.json"));
|
|
18
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,34 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@indigoai/mcp-companion",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "One MCP connector for every indigo.ai environment, with sign-ins kept on the person's computer",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"indigo-mcp-companion": "dist/index.js"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"dist"
|
|
11
|
+
],
|
|
12
|
+
"engines": {
|
|
13
|
+
"node": ">=20"
|
|
14
|
+
},
|
|
15
|
+
"scripts": {
|
|
16
|
+
"build": "tsc -p tsconfig.build.json",
|
|
17
|
+
"typecheck": "tsc",
|
|
18
|
+
"test": "vitest run"
|
|
19
|
+
},
|
|
20
|
+
"dependencies": {
|
|
21
|
+
"@modelcontextprotocol/sdk": "1.32.1",
|
|
22
|
+
"@napi-rs/keyring": "^2.1.1",
|
|
23
|
+
"jose": "^6.2.12",
|
|
24
|
+
"open": "^11.0.4",
|
|
25
|
+
"proper-lockfile": "^4.1.2",
|
|
26
|
+
"zod": "^3.25.76"
|
|
27
|
+
},
|
|
28
|
+
"devDependencies": {
|
|
29
|
+
"@types/node": "^22.20.5",
|
|
30
|
+
"@types/proper-lockfile": "^4.1.4",
|
|
31
|
+
"typescript": "^5.9.3",
|
|
32
|
+
"vitest": "^3.2.7"
|
|
33
|
+
}
|
|
34
|
+
}
|