@agentvalet/mcp-server 0.3.7 → 0.3.10

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/dist/bind.js ADDED
@@ -0,0 +1,149 @@
1
+ // First-run invite bind for AgentValet MCP server.
2
+ //
3
+ // Triggered when INVITE_BIND_SECRET is set in env and no agent identity
4
+ // (AGENT_ID + private key) is yet available. We generate an RSA-2048
5
+ // keypair locally, POST the public key + bind_secret to /v1/invites/bind,
6
+ // and persist the returned identity + private key to ~/.agentvalet/.
7
+ //
8
+ // The bind_secret is one-shot, with a 30-minute TTL — the proxy returns
9
+ // 410 on replay. We DO NOT retry, because a 410 either means the secret
10
+ // was already consumed by an earlier run (so the identity should already
11
+ // be on disk) or it expired (the invitee needs a re-issue).
12
+ //
13
+ // Persistence layout (created with permission 0700 on the parent dir):
14
+ // ~/.agentvalet/agent.key PEM-encoded private key, mode 0600
15
+ // ~/.agentvalet/agent.json { agent_id, owner_id, proxy_url, bound_at }
16
+ import { generateKeyPairSync } from "node:crypto";
17
+ import { mkdirSync, writeFileSync, existsSync, readFileSync } from "node:fs";
18
+ import { homedir } from "node:os";
19
+ import { join } from "node:path";
20
+ const AGENTVALET_DIR = join(homedir(), ".agentvalet");
21
+ const KEY_PATH = join(AGENTVALET_DIR, "agent.key");
22
+ const IDENTITY_PATH = join(AGENTVALET_DIR, "agent.json");
23
+ export function getAgentvaletDir() {
24
+ return AGENTVALET_DIR;
25
+ }
26
+ export function getKeyPath() {
27
+ return KEY_PATH;
28
+ }
29
+ export function getIdentityPath() {
30
+ return IDENTITY_PATH;
31
+ }
32
+ /**
33
+ * Reads a previously-bound identity from disk, if one exists. Returns
34
+ * null when the file is absent or unparseable — callers should treat
35
+ * that as "no identity yet, proceed with bind".
36
+ */
37
+ export function readBoundIdentity() {
38
+ if (!existsSync(IDENTITY_PATH))
39
+ return null;
40
+ try {
41
+ const raw = readFileSync(IDENTITY_PATH, "utf-8");
42
+ const parsed = JSON.parse(raw);
43
+ if (typeof parsed.agent_id === "string" &&
44
+ typeof parsed.owner_id === "string" &&
45
+ typeof parsed.proxy_url === "string") {
46
+ return parsed;
47
+ }
48
+ return null;
49
+ }
50
+ catch {
51
+ return null;
52
+ }
53
+ }
54
+ /**
55
+ * Returns the disk-stored private key PEM if present, otherwise null.
56
+ */
57
+ export function readBoundPrivateKey() {
58
+ if (!existsSync(KEY_PATH))
59
+ return null;
60
+ try {
61
+ return readFileSync(KEY_PATH, "utf-8").trim();
62
+ }
63
+ catch {
64
+ return null;
65
+ }
66
+ }
67
+ /**
68
+ * Generates an RSA-2048 keypair, POSTs the public key + bind_secret to
69
+ * the proxy, and persists both the returned identity and the private
70
+ * key to ~/.agentvalet/.
71
+ *
72
+ * Caller is responsible for deciding when to invoke (e.g. only when
73
+ * INVITE_BIND_SECRET is set and no identity already exists on disk).
74
+ */
75
+ export async function attemptInviteBind(opts) {
76
+ const { publicKey, privateKey } = generateKeyPairSync("rsa", {
77
+ modulusLength: 2048,
78
+ publicKeyEncoding: { type: "spki", format: "pem" },
79
+ privateKeyEncoding: { type: "pkcs8", format: "pem" },
80
+ });
81
+ const url = `${opts.proxyUrl.replace(/\/$/, "")}/v1/invites/bind`;
82
+ // 15s hard timeout: Claude Desktop kills the transport at ~12-15s of
83
+ // silence. If the proxy hangs, fail visibly with stderr rather than
84
+ // letting the host record an unexplained "transport closed".
85
+ const ac = new AbortController();
86
+ const timer = setTimeout(() => ac.abort(), 15_000);
87
+ let res;
88
+ try {
89
+ res = await fetch(url, {
90
+ method: "POST",
91
+ headers: { "Content-Type": "application/json" },
92
+ body: JSON.stringify({
93
+ bind_secret: opts.bindSecret,
94
+ public_key_pem: publicKey,
95
+ }),
96
+ signal: ac.signal,
97
+ });
98
+ }
99
+ catch (err) {
100
+ if (err instanceof Error && err.name === "AbortError") {
101
+ throw new Error("Bind request timed out after 15s — proxy unreachable or slow.");
102
+ }
103
+ throw err;
104
+ }
105
+ finally {
106
+ clearTimeout(timer);
107
+ }
108
+ if (!res.ok) {
109
+ let detail = `HTTP ${res.status}`;
110
+ try {
111
+ const body = await res.json();
112
+ if (body.error)
113
+ detail = body.error;
114
+ }
115
+ catch {
116
+ // ignore
117
+ }
118
+ if (res.status === 410) {
119
+ throw new Error(`Bind secret rejected (${detail}). It was either already used or expired — ask the inviting manager to re-issue.`);
120
+ }
121
+ throw new Error(`Invite bind failed: ${detail}`);
122
+ }
123
+ const payload = await res.json();
124
+ if (!payload.agent_id || !payload.owner_id || !payload.proxy_url) {
125
+ throw new Error("Bind succeeded but response was missing required fields");
126
+ }
127
+ const identity = {
128
+ agent_id: payload.agent_id,
129
+ owner_id: payload.owner_id,
130
+ proxy_url: payload.proxy_url,
131
+ bound_at: new Date().toISOString(),
132
+ };
133
+ persistBindArtifacts(identity, privateKey);
134
+ return { identity, privateKeyPem: privateKey };
135
+ }
136
+ /**
137
+ * Writes the private key + identity to ~/.agentvalet/. The directory
138
+ * is created with 0700 if it does not yet exist; the key file is
139
+ * written with 0600. Identity is non-secret (no token material) but
140
+ * we keep it inside the same directory for cleanup symmetry.
141
+ *
142
+ * Exposed so tests can verify the on-disk layout without making a
143
+ * real HTTP call.
144
+ */
145
+ export function persistBindArtifacts(identity, privateKeyPem) {
146
+ mkdirSync(AGENTVALET_DIR, { recursive: true, mode: 0o700 });
147
+ writeFileSync(KEY_PATH, privateKeyPem, { mode: 0o600 });
148
+ writeFileSync(IDENTITY_PATH, JSON.stringify(identity, null, 2));
149
+ }
package/dist/config.js CHANGED
@@ -1,25 +1,105 @@
1
1
  import { readPrivateKeyFromEnv } from "./pem.js";
2
2
  import { importPKCS8 } from "jose";
3
+ import { attemptInviteBind, readBoundIdentity, readBoundPrivateKey, } from "./bind.js";
4
+ const DEFAULT_PROXY_URL = "https://api.agentvalet.ai";
5
+ /**
6
+ * Resolves the agent's identity + private key. Three paths:
7
+ *
8
+ * 1. Env-based — AGENT_ID + OWNER_ID + PROXY_URL + AGENT_PRIVATE_KEY*
9
+ * provided. Legacy path; preserved unchanged.
10
+ *
11
+ * 2. Disk identity — env vars are missing but ~/.agentvalet/agent.json
12
+ * and ~/.agentvalet/agent.key exist (e.g. from a previous bind).
13
+ * Read them and proceed as if env had been set.
14
+ *
15
+ * 3. Invite-bind first run — INVITE_BIND_SECRET is set, no identity
16
+ * is yet on disk, and no AGENT_ID env. Generate a keypair, POST
17
+ * /v1/invites/bind, persist the result, then proceed.
18
+ *
19
+ * Order matters: env wins (explicit > implicit), then disk identity,
20
+ * then invite-bind. The bind path runs at most once per machine —
21
+ * the secret is consumed after first use.
22
+ */
23
+ // Treat empty strings AND unresolved MCPB template placeholders (e.g.
24
+ // "${user_config.agent_id}") as "not set". Claude Desktop on some platforms
25
+ // passes the literal placeholder through when a user_config field has no
26
+ // value and no manifest default — that would otherwise false-trigger the
27
+ // env-based Path 1 below and skip the invite-bind handshake.
28
+ function envOrNull(name) {
29
+ const v = process.env[name];
30
+ if (v === undefined)
31
+ return null;
32
+ const t = v.trim();
33
+ if (t === "")
34
+ return null;
35
+ if (t.startsWith("${") && t.endsWith("}"))
36
+ return null;
37
+ return t;
38
+ }
3
39
  export async function validateConfig() {
40
+ // Path 1 — env-based (legacy).
41
+ const envAgentId = envOrNull("AGENT_ID");
42
+ const envOwnerId = envOrNull("OWNER_ID");
43
+ const envProxyUrl = envOrNull("PROXY_URL");
44
+ if (envAgentId && envOwnerId && envProxyUrl) {
45
+ return buildConfig({
46
+ agentId: envAgentId,
47
+ ownerId: envOwnerId,
48
+ proxyUrl: envProxyUrl,
49
+ });
50
+ }
51
+ // Path 2 — disk identity from a previous bind.
52
+ const diskIdentity = readBoundIdentity();
53
+ const diskKey = readBoundPrivateKey();
54
+ if (diskIdentity && diskKey) {
55
+ return buildConfig({
56
+ agentId: envAgentId ?? diskIdentity.agent_id,
57
+ ownerId: envOwnerId ?? diskIdentity.owner_id,
58
+ proxyUrl: envProxyUrl ?? diskIdentity.proxy_url,
59
+ });
60
+ }
61
+ // Path 3 — first-run invite bind.
62
+ const inviteBindSecret = envOrNull("INVITE_BIND_SECRET");
63
+ if (inviteBindSecret) {
64
+ const proxyUrl = (envProxyUrl ?? DEFAULT_PROXY_URL).replace(/\/$/, "");
65
+ process.stderr.write(`[mcp-server] First-run invite bind against ${proxyUrl}…\n`);
66
+ try {
67
+ const { identity } = await attemptInviteBind({
68
+ bindSecret: inviteBindSecret,
69
+ proxyUrl,
70
+ });
71
+ process.stderr.write(`[mcp-server] Bound as ${identity.agent_id} (owner ${identity.owner_id}). Key persisted to ~/.agentvalet/agent.key\n`);
72
+ return buildConfig({
73
+ agentId: identity.agent_id,
74
+ ownerId: identity.owner_id,
75
+ proxyUrl: identity.proxy_url,
76
+ });
77
+ }
78
+ catch (err) {
79
+ process.stderr.write(`[mcp-server] Invite bind failed: ${err instanceof Error ? err.message : String(err)}\n`);
80
+ process.exit(1);
81
+ }
82
+ }
83
+ // Nothing usable — fall through to the original missing-env diagnostic.
4
84
  const missing = [];
5
85
  for (const key of ["AGENT_ID", "OWNER_ID", "PROXY_URL"]) {
6
86
  if (!process.env[key])
7
87
  missing.push(key);
8
88
  }
9
- if (missing.length > 0) {
10
- process.stderr.write(`[mcp-server] Missing required environment variables: ${missing.join(", ")}\n`);
11
- process.exit(1);
12
- }
13
- const agentId = process.env.AGENT_ID;
14
- const ownerId = process.env.OWNER_ID;
15
- const proxyUrl = process.env.PROXY_URL.replace(/\/$/, "");
89
+ process.stderr.write(`[mcp-server] Missing required environment variables: ${missing.join(", ")}\n` +
90
+ `Either set them, run the invite-bind flow with INVITE_BIND_SECRET, ` +
91
+ `or restore ~/.agentvalet/agent.{key,json} from a previous bind.\n`);
92
+ process.exit(1);
93
+ }
94
+ async function buildConfig(args) {
95
+ const proxyUrl = args.proxyUrl.replace(/\/$/, "");
16
96
  let privateKeyPem = null;
17
97
  let privateKey = null;
18
98
  try {
19
99
  privateKeyPem = readPrivateKeyFromEnv();
20
100
  }
21
101
  catch {
22
- // No key provided — tools will return pending-activation response
102
+ // No key — tools will return pending-activation response.
23
103
  }
24
104
  if (privateKeyPem !== null) {
25
105
  try {
@@ -30,5 +110,5 @@ export async function validateConfig() {
30
110
  process.exit(1);
31
111
  }
32
112
  }
33
- return { agentId, ownerId, proxyUrl, privateKeyPem, privateKey };
113
+ return { agentId: args.agentId, ownerId: args.ownerId, proxyUrl, privateKeyPem, privateKey };
34
114
  }
package/dist/index.js CHANGED
@@ -1,3 +1,19 @@
1
+ // ── BOOT DIAGNOSTICS — must be FIRST executable code ─────────────────────
2
+ // Claude Desktop captures whatever the MCP server writes to stderr before
3
+ // the stdio transport handshake. If startup crashes silently (top-level
4
+ // await rejection, import error, unhandled native crash), Claude Desktop
5
+ // only logs "Server transport closed unexpectedly" with no detail. These
6
+ // handlers guarantee a stack lands in the log no matter what fails next.
7
+ process.stderr.write(`[mcp-server] boot v0.2.x | node=${process.version} | platform=${process.platform} | ` +
8
+ `env_keys=${Object.keys(process.env).filter((k) => k.startsWith("AGENT_") || k === "OWNER_ID" || k === "PROXY_URL" || k === "INVITE_BIND_SECRET").join(",") || "(none of expected)"}\n`);
9
+ process.on("uncaughtException", (err) => {
10
+ process.stderr.write(`[mcp-server] FATAL uncaughtException: ${err instanceof Error ? err.stack ?? err.message : String(err)}\n`);
11
+ process.exit(1);
12
+ });
13
+ process.on("unhandledRejection", (err) => {
14
+ process.stderr.write(`[mcp-server] FATAL unhandledRejection: ${err instanceof Error ? err.stack ?? err.message : String(err)}\n`);
15
+ process.exit(1);
16
+ });
1
17
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
18
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
19
  import { CallToolRequestSchema, ListToolsRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
@@ -7,7 +23,16 @@ import { renderInstructions } from "./instructions.js";
7
23
  // ---------------------------------------------------------------------------
8
24
  // Startup env validation
9
25
  // ---------------------------------------------------------------------------
10
- const { agentId: AGENT_ID, ownerId: OWNER_ID, proxyUrl: PROXY_URL, privateKeyPem: AGENT_PRIVATE_KEY_RAW, privateKey } = await validateConfig();
26
+ let configResult;
27
+ try {
28
+ configResult = await validateConfig();
29
+ }
30
+ catch (err) {
31
+ process.stderr.write(`[mcp-server] FATAL validateConfig threw: ${err instanceof Error ? err.stack ?? err.message : String(err)}\n`);
32
+ process.exit(1);
33
+ }
34
+ const { agentId: AGENT_ID, ownerId: OWNER_ID, proxyUrl: PROXY_URL, privateKeyPem: AGENT_PRIVATE_KEY_RAW, privateKey } = configResult;
35
+ process.stderr.write(`[mcp-server] config ok | agent=${AGENT_ID} | owner=${OWNER_ID} | proxy=${PROXY_URL} | has_key=${!!privateKey}\n`);
11
36
  // ---------------------------------------------------------------------------
12
37
  // JWT signing
13
38
  // ---------------------------------------------------------------------------
@@ -316,11 +341,20 @@ async function fetchPlatformNamesForInstructions() {
316
341
  return undefined;
317
342
  }
318
343
  }
319
- const bootPlatformNames = await fetchPlatformNamesForInstructions();
344
+ // NOTE: We intentionally do NOT prefetch platform names at boot. Doing so
345
+ // added a top-level await on the proxy and blocked the `initialize` response
346
+ // to Claude Desktop for several seconds (worse on cold Azure CA), causing
347
+ // host-side timeouts. The LLM learns the catalogue from list_platforms at
348
+ // runtime — boot-time enrichment was nice-to-have, not load-bearing.
320
349
  // ---------------------------------------------------------------------------
321
350
  // MCP server setup
322
351
  // ---------------------------------------------------------------------------
323
- const server = new Server({ name: "agentvalet", version: "1.0.0" }, { capabilities: { tools: {} }, instructions: renderInstructions(bootPlatformNames) });
352
+ const server = new Server({ name: "agentvalet", version: "1.0.0" }, { capabilities: { tools: {} }, instructions: renderInstructions(undefined) });
353
+ // Fire the platform-names fetch in the background after the server is up so
354
+ // it can't delay initialize. The result isn't surfaced to the host (MCP has
355
+ // no instructions-update message), but the network warmup primes the proxy
356
+ // and surfaces auth failures in the stderr boot diagnostics path.
357
+ void fetchPlatformNamesForInstructions().catch(() => { });
324
358
  server.setRequestHandler(ListToolsRequestSchema, async () => ({
325
359
  tools: [
326
360
  LIST_PLATFORMS_TOOL,
@@ -479,6 +513,20 @@ async function handleListPlatforms() {
479
513
  const body = await response.text();
480
514
  if (!response.ok)
481
515
  return errorContent(`Proxy error ${response.status}: ${body}`);
516
+ // Proxy wraps the payload as { data: { platforms, version }, _meta: {...} }
517
+ // but outputSchema declares the flat { platforms, version } shape, so the
518
+ // wrapped envelope fails strict structuredContent validation and the host
519
+ // surfaces "tool execution failed (no upstream body)". Unwrap .data.
520
+ const parsed = tryParseJson(body);
521
+ const inner = parsed && typeof parsed === "object" && parsed !== null && "data" in parsed
522
+ ? parsed.data
523
+ : parsed;
524
+ if (inner && typeof inner === "object") {
525
+ return {
526
+ content: [{ type: "text", text: body }],
527
+ structuredContent: inner,
528
+ };
529
+ }
482
530
  return jsonContent(body);
483
531
  }
484
532
  // Translates a fetch() failure into something an end-user can actually act on.
package/dist/pem.js CHANGED
@@ -1,27 +1,50 @@
1
1
  import { readFileSync } from "fs";
2
+ import { readBoundPrivateKey } from "./bind.js";
2
3
  /**
3
4
  * Reads the RS256 private key from environment variables, supporting four formats:
4
5
  * - AGENT_PRIVATE_KEY_B64: base64-encoded PEM
5
6
  * - AGENT_PRIVATE_KEY_PATH: path to a PEM file
6
7
  * - AGENT_PRIVATE_KEY: raw multi-line PEM or \n-escaped single-line PEM
8
+ *
9
+ * Falls back to the disk-persisted invite-bind key at
10
+ * ~/.agentvalet/agent.key when no env-based source is present. This is
11
+ * the path written by the invite-flow first-run bind (see bind.ts) —
12
+ * having pem.ts honour it means subsequent invocations of the
13
+ * mcp-server don't need any env vars at all.
7
14
  */
15
+ // Treat empty + unresolved MCPB placeholders ("${user_config.foo}") as
16
+ // not-set — see config.ts for the same defence on identity envs.
17
+ function readEnv(name) {
18
+ const v = process.env[name];
19
+ if (v === undefined)
20
+ return null;
21
+ const t = v.trim();
22
+ if (t === "")
23
+ return null;
24
+ if (t.startsWith("${") && t.endsWith("}"))
25
+ return null;
26
+ return t;
27
+ }
8
28
  export function readPrivateKeyFromEnv() {
9
29
  // 1. Base64-encoded PEM
10
- if (process.env.AGENT_PRIVATE_KEY_B64) {
11
- return Buffer.from(process.env.AGENT_PRIVATE_KEY_B64, "base64").toString("utf-8").trim();
30
+ const b64 = readEnv("AGENT_PRIVATE_KEY_B64");
31
+ if (b64) {
32
+ return Buffer.from(b64, "base64").toString("utf-8").trim();
12
33
  }
13
34
  // 2. Path to PEM file
14
- if (process.env.AGENT_PRIVATE_KEY_PATH) {
35
+ const path = readEnv("AGENT_PRIVATE_KEY_PATH");
36
+ if (path) {
15
37
  try {
16
- return readFileSync(process.env.AGENT_PRIVATE_KEY_PATH, "utf-8").trim();
38
+ return readFileSync(path, "utf-8").trim();
17
39
  }
18
40
  catch (err) {
19
41
  throw new Error(`Cannot read AGENT_PRIVATE_KEY_PATH: ${err instanceof Error ? err.message : err}`);
20
42
  }
21
43
  }
22
44
  // 3. Raw PEM content (multi-line or \n-escaped)
23
- if (process.env.AGENT_PRIVATE_KEY) {
24
- const raw = process.env.AGENT_PRIVATE_KEY.trim();
45
+ const rawEnv = readEnv("AGENT_PRIVATE_KEY");
46
+ if (rawEnv) {
47
+ const raw = rawEnv;
25
48
  // Unescape \n sequences
26
49
  const unescaped = raw.replace(/\\n/g, "\n");
27
50
  // Wrap bare base64 blob without headers
@@ -30,5 +53,10 @@ export function readPrivateKeyFromEnv() {
30
53
  }
31
54
  return unescaped;
32
55
  }
33
- throw new Error("No private key provided. Set AGENT_PRIVATE_KEY, AGENT_PRIVATE_KEY_PATH, or AGENT_PRIVATE_KEY_B64.");
56
+ // 4. Disk fallback written by the invite-bind first-run flow.
57
+ const diskKey = readBoundPrivateKey();
58
+ if (diskKey)
59
+ return diskKey;
60
+ throw new Error("No private key provided. Set AGENT_PRIVATE_KEY, AGENT_PRIVATE_KEY_PATH, or AGENT_PRIVATE_KEY_B64, " +
61
+ "or run the invite-bind flow with INVITE_BIND_SECRET.");
34
62
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentvalet/mcp-server",
3
- "version": "0.3.7",
3
+ "version": "0.3.10",
4
4
  "description": "AgentValet MCP server — lets AI agents call approved platforms via the AgentValet proxy",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",